text
stringlengths
37
1.41M
imiona = ['Artur', 'Barbara', 'Czesław'] print(imiona) indeks = int(input('Proszę podać indeks imienia do skasowania: ')) indeks_min = -1 * len(imiona) indeks_max = len(imiona) -1 if indeks_min <= indeks <= indeks_max : print('Kasowane imię to:', imiona.pop(indeks)) else: print('Nie ma elementu o takim indeksie') print(imiona)
while True: wyraz = input('Wpisz dowolny wyraz: ') if ' ' in wyraz: print('Wpisano spację') continue ile_znakow = len(wyraz) komunikat = 'Wyraz "{}" ma {} znaków.\n' \ 'Wyraz ten zaczyna się na literę "{}"'.format(wyraz, ile_znakow, wyraz[0]) print(komunikat)
import numpy import streamlit as sl """# Transportation Problem""" @sl.cache def random_problem(size: int): """Random Transportation Problem to solve""" a = numpy.random.rand(size) a /= a.sum() b = numpy.random.rand(size) b /= b.sum() c = numpy.random.rand(size, size) c /= c.sum() return a, b, c """## Random Test""" n = sl.slider("size", min_value=1, max_value=20) a, b, c = random_problem(n) """a, b""" sl.write(a) sl.write(b) """C""" sl.write(c) def solve(a, b, c, lm: float, loop_times: int): """Transportation Problem, 最適輸送問題 Parameters ---------- a source vector b destination vector c cost matrix c[i][j] is the cost from a[i] to b[j] lm hyper parameter, lambda loop_times loop times for convergence """ n = len(a) assert lm > 0.0 k = numpy.exp(c * (-lm)) u = numpy.ones(n) for _ in range(loop_times): v = b / (numpy.transpose(k) @ u) u = a / (k @ v) p = numpy.transpose(u * numpy.transpose(k * v)) return p lm = sl.slider("lambda", min_value=0.1, max_value=100.0, step=0.1) sl.write("lambda=", lm) loop_times = sl.slider("loop_times", min_value=10, max_value=100) p = solve(a, b, c, lm, loop_times) sl.write("P", p) sl.write("cost", numpy.sum(c * p)) """# Sorting Problem""" @sl.cache def random_array(size: int): """Sorting this x""" x = numpy.random.rand(n) return x def my_sort(x, lm: float, iter: int = 200): """Sorting with Transportation Problem Solver""" n = len(x) y = numpy.array(range(n)) a = numpy.ones(n) b = numpy.ones(n) c = numpy.array([[(x[i] - y[j]) ** 2.0 for j in range(n)] for i in range(n)]) c /= c.sum() p = solve(a, b, c, lm, iter) return p """## Random Array""" n = sl.slider("array size", min_value=1, max_value=20) lm = sl.slider("lambda!", min_value=1, max_value=2000) x = random_array(n) sl.write("sorting x:", x) p = my_sort(x, lm) s = n * numpy.transpose(p) @ x sl.write("Sorted(x)", s) acc = numpy.array(range(1, n + 1)) / n r = n * n * p @ acc sl.write("Rank(x)", r) """## Sorting 3 items""" n = 3 a = sl.slider("item_a", min_value=0.0, max_value=10.0, step=0.1) b = sl.slider("item_b", min_value=0.0, max_value=10.0, step=0.1) c = sl.slider("item_c", min_value=0.0, max_value=10.0, step=0.1) x = [a, b, c] sl.write("sorting x:", x) lm = 300.0 p = my_sort(x, lm, iter=3000) sl.write("Optimal Transprot", p) s = numpy.transpose(p) @ x sl.write("Sorted(x)", s) ranks = numpy.array(range(1, n + 1)) # [1, 2, ..., n] r = p @ ranks sl.write("Rank(x)", r)
#!/usr/bin/env python3 """ Laszlo Szathmary, 2014 ([email protected]) Print just the name of the current directory. For instance, if you are in "/home/students/solo", then this script will print just "solo". The output is also copied to the clipboard. Usage: here Last update: 2017-01-08 (yyyy-mm-dd) """ import os import sys from lib.clipboard import text_to_clipboards def main(): text = os.path.split(os.getcwd())[1] print('# copied to the clipboard', file=sys.stderr) print(text) text_to_clipboards(text) ############################################################################## if __name__ == "__main__": main()
# List of Pies pies = ["Pecan", "Apple Crisp","Bean", "Bannoffee","Black Bun", "Blueberry", "Buko","Burek", "Tamale","Steak"] greeting = ("Welcome to the House of Pies! Here are our pies: --------------------------------------------------------------------- \n(1) Pecan, (2) Apple Crisp, (3) Bean, (4) Banoffee, (5) Black Bun, (6) Blueberry, (7) Buko, (8) Burek, (9) Tamale, (10) Steak") #order count count = [0,0,0,0,0,0,0,0,0,0] new_order = "Y" while "Y": order_form = int(input(f' {greeting} \n Enter Pie No. to place order. ')) pindex = order_form - 1 #start the count if order_form in range(1,11): print( f"\n Great! We'll have that {pies[pindex]} right out for you.") count[pindex] += 1 #count2[pindex] += 1 elif order_form == 0 or order_form > 10: print("\nTo order, enter the correct pie number.") new_order = input("Do you want to order another pie? Y/N ").upper() if new_order == "N": print("\n You purchased:") for i in range(10): print(f"{count[i]} {pies[i]}") break
#!/usr/bin/env python # coding: utf-8 # In[1]: class Solution(object): def merge_sort(self, nums): if len(nums)<2:#當nums於2時 return nums#回傳nums else: left=nums[:len(nums)//2] #左邊數值 right=nums[len(nums)//2:]#右側數值 return merge(mergeSort(left), mergeSort(right))#回傳左右數值 def merge(self,left,right): a=0#紀錄left的位置 b=0#紀錄right的位置 c=[]#用來放置比較後的數值 while a<len(left) and b<len(right):#當2個list的值都沒跑完時 if left[a]<=right[b]: c.append(left[a])#把left第a個值存到c裡 a+=1#因為左邊第一個排序完成,所以換第二個 else: c.append(right[b])#把right第b個值存到c裡 b+=1#因為右邊第一個排序完成,所以換第二個 while a<len(left):#左方有值時執行的while迴圈 c.append(left[a])#將左方執行結果加進c裡面 a+=1 while b<len(right)::#右方有值時執行的while迴圈 c.append(right[b];#將右方執行結果加進c裡面 return c#回傳c
myFile = open("spam2.txt") total = 0 count = 0 average = 0 for line in myFile: if line.find("From ") >= 0: startEmail = line.find(" ") endEmail = line.find(" ", startEmail + 1) fromEmail = line[startEmail:endEmail] if line.find("To") >= 0: startEmail = line.find(" ") endEmail = line.find(" ", startEmail + 1) toEmail = line[startEmail:endEmail] if line.find("X-DSPAM-Confidence") >= 0: startConfidence = line.find(" ") endConfidence = len(line) num = line[startConfidence:endConfidence - 1] num = float(num) total = total + num count = count + 1 if (num > 0.9): print("From = ", fromEmail) print("To = ", toEmail) average = total / count print("Average: ", average)
import random #随机数 secrect=random.randint(1,10) #自定义函数 用于返回最大值 def getMaxVal(val1,val2): if(val1>=val2): return val1 else: return val2 print('-------------测试程序---------------') maxtimes=8 nowtime=0 while nowtime<8: temp=input("请输入数字:") guess=int(temp) if guess==secrect: print("大叔大婶大所多") print("fsdlfksdklfjsdlkjf") haveguess=1 nowtime=8 else: if guess>secrect: print("大了!!"); else: print("小了!!"); nowtime=nowtime+1 if nowtime<8: print("您还有"+str(maxtimes-nowtime)+"次机会") print(str(getMaxVal(1,9))) print("游戏结束!")
import numpy as np import matplotlib.pyplot as plt #read the data data = np.genfromtxt('kc_house_data.csv',delimiter=",") # read the data data =np.delete(data,0,axis=0) X = data[:, 19].reshape(-1,1) # -1 tells numpy to figure out the dimension by itself ones = np.ones([X.shape[0], 1]) # create a array containing only ones X = np.concatenate([ones, X],1) # cocatenate the ones to X matrix y = data[:, 2].reshape(-1,1) # create the y matrix plt.scatter(data[:, 19].reshape(-1,1), y) # setting learning rates and epoches alpha = 0.0001 iters = 1000 #initialize hypter parameter # theta = thera0 +theta1*X theta = np.array([[1.0, 1.0]]) def computeCost(X, y, theta): inner = np.power(((X @ theta.T) - y), 2) # @ means matrix multiplication of arrays. If we want to use * for multiplication we will have to convert all arrays to matrices return np.sum(inner) / ( 2*len(X)) def gradientDescent(X, y, theta, alpha, iters): for i in range(1000): theta = theta - (alpha/len(X)) * np.sum((X @ theta.T - y) * X, axis=0) cost = computeCost(X, y, theta) if i % 10 == 0: # just look at cost every ten loops for debugging print(cost) return (theta, cost) g, cost = gradientDescent(X, y, theta, alpha, iters) print(g, cost)
from math import floor num = float(input("Digite um numero: ")) inte = floor(num) print("O numero {} tem a parte inteira {}".format(num, inte))
# Python program showing # use of __call__() method class MyDecorator: def __init__(self, function): print("__init__") self.function = function @staticmethod def __call__(self): print("__call__") # We can add some code # before function call self.function() # We can also add some code # after function call. # adding class decorator to the function @MyDecorator def function(): print("GeeksforGeeks") function()
# @cache(times=3) # def some_function(): # pass # Would give out cached value up to times number only. Example: import functools from typing import Callable def cache(times: int) -> Callable: def cache_decorator(func: Callable) -> Callable: """ Accepts a functions Returns cashed function """ cache_dict: dict[tuple, str] = {} @functools.wraps(func) def wrapper(*args): if args in cache_dict and cache_dict[args][1] <= times: result = cache_dict[args][0] cache_dict[args][1] += 1 else: result = func(*args) count = 1 cache_dict[args] = [result, count] return result return wrapper return cache_decorator
""" Write a function that accepts another function as an argument. Then it should return such a function, so the every call to initial one should be cached. def func(a, b): return (a ** b) ** 2 cache_func = cache(func) some = 100, 200 val_1 = cache_func(*some) val_2 = cache_func(*some) assert val_1 is val_2 """ import functools from typing import Callable def cache(func: Callable) -> Callable: """ Accepts a functions Returns cashed function """ cache: dict[tuple, str] = {} @functools.wraps(func) def wrapper(*args): if args in cache: result = cache[args] else: result = func(*args) cache[args] = result return result return wrapper
""" Написать декоратор instances_counter, который применяется к любому классу и добавляет ему 2 метода: get_created_instances - возвращает количество созданых экземпляров класса reset_instances_counter - сбросить счетчик экземпляров, возвращает значение до сброса Имя декоратора и методов не менять Ниже пример использования """ def instances_counter(cls): class CounterClass(cls): counter = 0 def __init__(self, *args, **kwargs): super().__init__(*args, *kwargs) self.increase_counter() @classmethod def increase_counter(cls): cls.counter += 1 @classmethod def get_created_instances(cls): return cls.counter @classmethod def reset_instances_counter(cls): total_instances = cls.counter cls.counter = 0 return total_instances return CounterClass
#Accept a file name from user and print extension of that. a=input("enter the filename") s=a.split(".") j="." print(j+s[-1])
import csv with open("file.txt","r")as f: reader=csv.reader(f) for row in reader: print(row)
#Fibonacci series of N terms . n=int(input("enter the number")) coun=1 n1=0 n2=1 sum=0 print("fibanacci series:\n",end='') while(coun<=n): print(sum,end="\n") coun+=1 n1=n2 n2=sum sum=n1+n2
#Display first and last color. ls=[] print("enter the colors") b=input("").split(",") ls.append(b) print(b[0]) print(b[-1])
people = 50 cars = 30 trucks = 30 # if there are more cars than people, print the line below if cars > people: print(">>>> first if:", cars, people) # DEBUGGING print("We should take the cars.") # if there are not more cars than people but less, print the line below elif cars < people: print(">>>> first elif:", cars, people) # DEBUGGING print("We should not take the cars.") # if there are neither more nor less cars than people, print the line below else: print(">>>> first else:", cars, people) # DEBUGGING print("We can't decide.") #### # if there are more trucks than cars, print line below if trucks > cars: print(">>>> second if:", trucks, cars) # DEBUGGING print("That's too many trucks.") # if there are not more trucks than cars but less, print line below elif trucks < cars: print(">>>> second elif:", trucks, cars) # DEBUGGING print("Maybe we could take the trucks.") # if there are neither more nor less trucks than cars, print line below else: print(">>>> second else:", trucks, cars) # DEBUGGING print("We still can't decide.") #### # if there are more people than trucks, print line below if people > trucks: print(">>>> third if:", people, trucks) # DEBUGGING print("Alright, let's just take the trucks.") # if there are not more people than trucks, print line below else: print(">>>> third else:", people, trucks) # DEBUGGING print("Fine, let's stay home then.")
from sys import exit # Make the start of the game def start(): print("You wake up half naked on the ground.") print("Around you are massive trees surrounded by magical blue mist.") print("Far down the hill in front, you see a little village filled with blue skinned people.") print("You see a guard post with two armed guards a little bit to the right.") print("On a clearence to the left is a strange rift in space, a portal.") print("You can't see clearly what's behind you because of all the mist.") choice = input("> ") if choice == "front": village() if choice == "back": wolf() if choice == "right": guard_post() if choice == "left": rift() else: dead("You fall over a a rock and die.") # Make the village part def village(): print("After getting through some murmur in the center you approach a cloacked old lady.") print("She asks you: 'Left or Right?'") choice = input("> ") if choice == "left": print("The lady reveals herself as a witch and shoots a death spell out of her left hand.") dead("You turn into dust.") if choice == "right": print("The lady summons a rift from her right hand and pushes you through with a magic blast.") abyss() else: print("She turns into a witch screaming 'YOU FOOL!' and throws a volcano spell over you.") dead("You turned into fumes.") # Make the wolf part def wolf(): print("You stumble through the thick fog and see two eyes shine through.") print("Do you go towards them or run?") choice = input("> ") if choice == "go" or "towards": print("A massive black wolf reveals himself and his fangs.") dead("You're dog food now.") if choice == "run": start() else: wolf() # Make the rift part def rift(): print("1") choice = input("> ") # Make the guard post part def guard_post(): print("1") choice = input("> ") # Second Phase: The Abyss def dead(why): print(why, "Good job!") exit(0) start()
#!/usr/bin/env python3 from vehicle import vehicle from abc import ABC,abstractmethod class bike(vehicle): def __init__(self,name,color,wheel): super().__init__(name,color,wheel) def wheelie(length): for i in range(0,length): print("WEEE!") def makeSound(): print("BRRRING BRRRING")
# ###### 1 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # sm1 = int(input("enter marks of first subject :")) # sm2 = int(input("enter marks of Second subject :")) # sm3 = int(input("enter marks of third subject :")) # sm4 = int(input("enter marks of forth subject :")) # sm5 = int(input("enter marks of fivfth subject :")) # # Avarage_Of_marks = (sm1 + sm2+ sm3 + sm4 + sm5)/5 # # if Avarage_Of_marks >= 60: # print("First Division") # elif Avarage_Of_marks >=50 and Avarage_Of_marks <=59: # print("Second division ") # elif Avarage_Of_marks >=40 and Avarage_Of_marks <=49: # print('Third Division') # else: # print("you are fail") # ###### 2 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # sm1 = int(input("enter marks of first subject :")) # sm2 = int(input("enter marks of Second subject :")) # sm3 = int(input("enter marks of third subject :")) # # if sm1 >= 60 and sm2 >= 50 and sm3 >= 40: # print("You are admitted ot professional college ") # else: # print("Sorry you are admitted to professional college") # sm1 = int(input("enter marks of first maths :")) # sm2 = int(input("enter marks of Second physics :")) # sm3 = int(input("enter marks of third subject :")) # # if sm1 + sm2>=150: # print("you qualified for admission ") # else: # print("Sorry you are not able in qualifying exam") # ###### 3 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # print("Enter 1 to find the area of rectange : ") # print("Enter 2 to find the area of Circle : ") # print("Please Enter you choice --> :",end = "") # # p1 = int(input()) # if p1 == 1: # l = int(input("Enter the length of rectagle : ")) # b = int(input("Enter the breadth of rectagle : ")) # area = l*b # print(f"Area of the circle is {area}") # # elif p1 == 2: # r = int(input("Enter the readious of rectagle : ")) # area = 3.14*r*r # print(f"Area of the circle is {area}") # ######## 4 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # print("Enter 1 to find the addition of two numbers : ") # print("Enter 2 to find the Sbutraction of two numbers : ") # print("Enter 3 to find the multiplication of two numbers : ") # print("Enter 4 to find the Division of two numbers : ") # print("Enter 5 to find the inverse of two numbers : ") # print("Enter 6 to find the Sqaure of two numbers : ") # print("Enter 7 to find the Cube of two numbers : ") # # i = int(input("Please Enter you Choice to perform operation : ")) # if i >=1 and i <=7: # x = int(input("Enter the value of x : ")) # elif i >=1 and i <=4: # y = int(input("Enter the value of y : ")) # # if i == 1 : # z = x + y # print(f"Sum of two numbers is {z}") # # elif i == 2 : # z = x - y # print(f"Subraction of two numbers is {z}") # # elif i == 3 : # z = x * y # print(f"Multiplication of two numbers is {z}") # # elif i == 4 : # z = x / y # print(f"Division of two numbers is {z}") # # elif i == 5 : # z = 1/x # print(f"Inverse of x number is {z}") # # elif i == 6 : # z = x*x # print(f"Square of x number is {z}") # # elif i == 7 : # z = x*x*x # print(f"Cube of x number is {z}") # # else: # print("Invalid choice") ####### 5 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # Balance = 2000 # while True: # print("\n\n\nEnter code w for withdraw ") # print("Enter code d for deposit ") # print("Enter code c for Checking balance ") # print("Enter code e for exit ") # i = input(" \n\nPlease Enter your Choice : ") # # if i == "d": # amount = int(input("Enter the amount you want to Deposit : ")) # Balance = amount+Balance # print("Deposit Completed Succefully ") # # elif i == "w": # class NotSufficientAmount(Exception): # def __init__(self,value): # self.value = value # amount = int(input("Enter the amount you want to Withdraw : ")) # try: # if Balance <= amount: # raise NotSufficientAmount("UnSufficient Amount in the bank") # except NotSufficientAmount as e: # print(e.args) # else: # Balance = Balance - amount # print("Withdraw Amount Successfully") # finally: # print("Sources closed successfully") # # elif i == "c": # print(f"Total amount in the bank is {Balance}") # # elif i == "e": # break # # else: # print("Pleasee Select the valid Choice ")
"""CPU functionality.""" import sys class CPU: """Main CPU class.""" def __init__(self): """Construct a new CPU.""" self.ram = [0] * 256 self.register = [0] * 8 self.pc = 0 self.sp = 7 self.halt = False self.fl = 0b00000000 self.LDI = 0b10000010 self.PRN = 0b01000111 self.HLT = 0b00000001 self.MUL = 0b10100010 self.ADD = 0b10100000 self.POP = 0b01000110 self.PUSH = 0b01000101 self.CMP = 0b10100111 self.JEQ = 0b01010101 self.JNE = 0b01010110 self.JMP = 0b01010100 def push(self): self.register[self.sp] -= 1 address = self.ram[self.pc + 1] value = self.register[address] top_loc = self.register[self.sp] self.ram[top_loc] = value self.pc += 2 def pop(self): top_stack_val = self.register[self.sp] reg_addr = self.ram[self.pc + 1] self.register[reg_addr] = self.ram[top_stack_val] self.register[self.sp] += 1 self.pc += 2 def ram_read(self, mdr): return self.ram[mdr] def ram_write(self, value, address): self.ram[address] = value def load(self, file): """Load a program into memory.""" address = 0 # For now, we've just hardcoded a program: with open(file, "r") as program_data: # remove whitespaces and comments and store in a new list program = [] for line in program_data: code_and_comments = line.split("#") code = code_and_comments[0] code = code.strip() if len(code) > 0: program.append(int(code, 2)) # program = [ # # From print8.ls8 # 0b10000010, # LDI R0,8 # 0b00000000, # 0b00001000, # 0b01000111, # PRN R0 # 0b00000000, # 0b00000001, # HLT # ] for instruction in program: self.ram[address] = instruction address += 1 def hlt(self): self.pc += 1 self.halt = True def mult(self): self.alu("MUL", 0, 1) self.pc += 3 def add(self): self.alu("ADD", 0, 0) self.pc += 3 def alu(self, op, reg_a, reg_b): """ALU operations.""" if op == "ADD": self.register[reg_a] += self.register[reg_b] elif op == "MUL": self.register[reg_a] *= self.register[reg_b] elif op == "CMP": if self.register[reg_a] > self.register[reg_b]: self.fl = 0b00000010 elif self.register[reg_a] == self.register[reg_b]: self.fl = 0b00000001 elif self.register[reg_a] < self.register[reg_b]: self.fl = 0b00000100 else: raise Exception("Unsupported ALU operation") def trace(self): """ Handy function to print out the CPU state. You might want to call this from run() if you need help debugging. """ print(f"TRACE: %02X | %02X %02X %02X |" % ( self.pc, #self.fl, #self.ie, self.ram_read(self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2) ), end='') for i in range(8): print(" %02X" % self.register[i], end='') print() def ldi(self): address = self.ram[self.pc + 1] value = self.ram[self.pc + 2] self.register[address] = value self.pc += 3 def prn(self): address = self.ram[self.pc + 1] value = self.register[address] print(value) self.pc += 2 def comp(self): self.alu("CMP", 0, 1) self.pc += 3 def jeq(self): flag = str(self.fl)[-1] address = self.ram[self.pc + 1] if int(flag) == 1: self.pc = self.register[address] else: self.pc += 2 def jne(self): flag = str(self.fl)[-1] address = self.ram[self.pc + 1] if int(flag) != 1: self.pc = self.register[address] else: self.pc += 2 def jmp(self): address = self.ram[self.pc + 1] self.pc = self.register[address] def run(self): """Run the CPU.""" # while self.halt is False: # cmd = self.ram[self.pc] # if cmd == 0b10000010: # reg = self.ram[self.pc + 1] # value = self.ram[self.pc + 2] # self.register[reg] = value # self.pc += 3 # elif cmd == 0b01000111: # reg = self.ram[self.pc + 1] # print(self.register[reg]) # self.pc += 2 # elif cmd == 0b00000001: # self.halt = True # elif cmd == 0b10100010: # regA = self.ram[self.pc + 1] # regB = self.ram[self.pc + 2] # self.alu("MUL", regA, regB) # self.pc += 3 # elif cmd == 0b01000110: #pop # self.pop() # elif cmd == 0b01000101: #push # self.push() branch_table = { self.LDI : self.ldi, self.PRN : self.prn, self.MUL : self.mult, self.ADD : self.add, self.HLT : self.hlt, self.PUSH : self.push, self.POP : self.pop, self.CMP : self.comp, self.JEQ : self.jeq, self.JNE : self.jne, self.JMP : self.jmp } self.register[self.sp] = 0xF4 self.halt = False while self.halt is False: ir = self.ram[self.pc] if ir in branch_table: branch_table[ir]() elif ir not in branch_table: print(f"Wrong instruction {ir} at address {self.pc}") sys.exit(1)
#! /usr/bin/env python # -*- coding: utf-8 -*- def fiat_shamir(): #Inicialización p=int(raw_input("\033[36m" +"Introduce el número primo secreto P: "+'\033[0;m')) q=int(raw_input("\033[36m" +"Introduce el número primo secreto Q: "+'\033[0;m')) N=p*q print "\033[35m" +"N="+str(N) +'\033[0;m' #Identificación secreta de A s=int(raw_input("\033[36m" +"Introduce el número secreto s: "+'\033[0;m')) v=(s**2)%N print "\033[35m" +"v="+str(v)+'\033[0;m' iteraciones=int(raw_input("\033[36m" +"Introduce el número de iteraciones a realizar: "+'\033[0;m')) for i in range(iteraciones): #Compromiso secreto de A x=int(raw_input("\033[36m" +"Introduce el número secreto x: "+'\033[0;m')) #Testigo a=(x**2)%N #Reto e=int(raw_input("\033[36m" +"Introduce el bit e: "+'\033[0;m')) #Respuesta if (e==0): y=x%N elif (e==1): y=(x*s)%N #Verificación if (e==0): print "\033[35m" +str(i+1)+"ª Iteracion: a="+str(a)+",y="+str(y)+ " comprobar que "+str(y)+"^2"+"(="+str(((y**2)%N)) + ") es igual a " +str(a)+"mod"+str(N)+"(="+ str((a%N))+")"+'\033[0;m' if(((y**2)%N)==a%N): print "\033[35m" +"Comprobación Correcta!"+'\033[0;m' elif (e==1): print "\033[35m" +str(i+1)+"ª Iteracion: a="+str(a)+",y="+str(y)+" comprobar que "+str(y)+"^2"+"(="+str(((y**2)%N)) +") es igual a " +str(a)+"*"+str(v)+"mod"+str(N)+"(="+ str(((a*v)%N))+")"+'\033[0;m' if(((y**2)%N)==((a*v)%N)): print "\033[35m" +"Comprobación Correcta!"+'\033[0;m' def menu(): #Muestra el menú salir=False print "\033[2J\033[1;1f" print "\033[36m" +"Carolina Álvarez Martín - alu0100944723"+'\033[0;m' print "\033[36m" +"P10:Algoritmo de Fiat-Shamir"+'\033[0;m' while not salir: print "\033[36m" +"¿Qué quieres hacer?"+'\033[0;m' print "\033[36m" +"1)Cifrar"+'\033[0;m' print "\033[36m" +"2)Salir"+'\033[0;m' opcion=raw_input("\033[36m" +"Introduce una opción:"+'\033[0;m' ) if opcion=="1": fiat_shamir() elif opcion=="2": salir=True else: print "\033[36m" +"Introduce 1 o 2 "'\033[0;m'
#! /usr/bin/env python # -*- coding: utf-8 -*- from random import sample from exponenciacion_rapida import * def test_lehman_peralta(p): #comprobación de los primos pequeños: primos=[2,3,5,7,11] print "\033[35m" +"Test de Lehman-Peralta para " + str(p) + ": "+'\033[0;m' print "\033[35m" +"1. Comprobamos que no sea divisible por los números primos pequeños: "+'\033[0;m' if (p in primos): print "\033[35m" +str(p)+ " es un número primo pequeño\n"+'\033[0;m' return True else: for i in primos: if(p%i==0) : print "\033[35m" +str(p)+" es divisible por "+str(i)+" por tanto no es primo.\n"+'\033[0;m' return False else: print "\033[35m" +str(p)+" no es divisible por "+str(i)+"."+'\033[0;m' print "\n" #aletorios print "\033[35m" +"2.Elegimos enteros(a) al azar entre 2 y " + str(p-1) + " y calculamos a[i]^p-1/2"+'\033[0;m' a =sample([x for x in range(2,p-1)],p/2) contador=0 for i in a: print "\033[35m" +"Calculamos "+ str(i)+"^" + str((p-1)/2)+"= " + str(exponenciacion_rapida(i,(p-1)/2,p))+ " mod"+str(p)+'\033[0;m' if(exponenciacion_rapida(i,(p-1)/2,p)==p-1 or exponenciacion_rapida(i,(p-1)/2,p)==1): if (exponenciacion_rapida(i,(p-1)/2,p)==p-1): contador=contador+1 else : print "\033[35m" +str(p) + " No es primo\n"+'\033[0;m' return False if(contador>=1): print "\033[35m" +str(p) + " Puede ser primo\n"+'\033[0;m' return True else: print "\033[35m" +str(p) + " No es primo\n"+'\033[0;m' return False
from datetime import datetime def fib(n): if (n <= 2): return 1 else: return fib(n - 1) + fib(n - 2) def run(n): start_time = datetime.now() res = fib(n) print("Calculating fib(%d) = %d took %s seconds" % (n, res, datetime.now() - start_time)) if __name__ == '__main__': run(2) run(5) run(10) run(20) run(30) run(40) run(60)
def get_all_powers_of_two(x): res = [] power_of_two = 1 while power_of_two <= x: if power_of_two & x != 0: res.append(power_of_two) power_of_two = power_of_two << 1 return res def run_tests(): assert get_all_powers_of_two(330) == [2, 8, 64, 256] assert get_all_powers_of_two(3) == [1, 2] assert get_all_powers_of_two(22) == [2, 4, 16] assert get_all_powers_of_two(0) == [] assert get_all_powers_of_two(1) == [1] if __name__ == '__main__': run_tests()
# Related blog post - https://algoritmim.co.il/2019/11/23/senate-evacuation/ import string def remove_senators(senators_counter, senators_to_evict): for senator in senators_to_evict: senators_counter[senator] -= 1 if senators_counter[senator] == 0: senators_counter.pop(senator) def format_results(eviction_plan_list): eviction_plan_list = ["".join(senators) for senators in eviction_plan_list] return " ".join(eviction_plan_list) def choose_next_to_evict(senators_counter): if len(senators_counter) == 2: return list(senators_counter.keys()) else: return [max(senators_counter, key=senators_counter.get)] def evict_the_senate_iter(senators_counter): eviction_plan = [] while len(senators_counter) > 0: senators_to_evict = choose_next_to_evict(senators_counter) remove_senators(senators_counter, senators_to_evict) eviction_plan.append(senators_to_evict) return format_results(eviction_plan) if __name__ == '__main__': num_test_cases = int(input()) for i in range(1, num_test_cases + 1): num_parties = int(input()) parties = [c for c in string.ascii_uppercase[:num_parties]] senators_count_per_party = [int(s) for s in input().split(" ")] counter = dict(zip(parties, senators_count_per_party)) print("Case #{}: {}".format(i, evict_the_senate_iter(counter)))
def fibsum(N): if N == 0: return 0 previous = 0 current = 1 while current <= N: tmp = current current = current + previous previous = tmp ########## here current >= A count = 0 remain = N while remain >= previous: count += 1 remain -= previous return count + fibsum(remain) if __name__ == '__main__': assert fibsum(0) == 0 assert fibsum(2) == 1 assert fibsum(8) == 1 assert fibsum(11) == 2 assert fibsum(12) == 3
COLORS = ["red", "blue", "green", "purple", "orange", "yellow"] COLORS_DICT = {color[0]: color for color in COLORS} CODE_LENGTH = 2 TOTAL_ROUNDS = 12 USER_INPUT_PROMPT = "Please enter your next guess. (r=red b=blue g=green p=purple o=orange y=yellow\n" USER_SCORE = "Bul: {}, Pgia: {}\n" USER_WON = "You Win!" USER_LOST = "You Lose!"
import math # find sum of an array/list. Diffculty: Easy def sum(A): if not A: return 0 if len(A)==1: return A[0] if len(A)>1: return A[0]+sum(A[1:]) # print(sum([1,2,3])) # find Minimum of an array. Diffculty: Easy def basicMin(A, currMin): if not A: return currMin if currMin>A[0]: currMin=A[0] return basicMin(A[1:],currMin) # optimized version of finding min. Diffculty: Easy def findMin(A, l, r): if l==r: return A[r] mid = math.floor((l+r)/2) leftMin = findMin(A,l , mid) rightMin = findMin(A, mid+1, r) return min(leftMin, rightMin) # print( findMin([3,1,2])) # checks if a string is a palindrom. Diffculty: medium def isPali(text): if len(text)<= 1: return 1 elif text[0] != text[len(text)-1]: return 0 else: temp = text[1:-1] return isPali(temp) # print( isPali('ssws') ) # reverse a list recursivly. Diffculty: Medium. def reverseList(A,rev): if not A: return reverseList(A[1:],rev) rev.append(A[0]) # rev = [] # reverseList([3,2,1],rev) # print(rev) # find a subsets of a set. Diffculty: Hard def print_set(subset): temp = [] for x in subset: if x!= None: temp.append(x) print(temp) def all_subsets(given_array): subset = [None] * len(given_array) helper(given_array,subset,0) def helper(given_array, subset, i): if i==len(given_array): print_set(subset) else: subset[i] = None helper(given_array,subset,i+1) subset[i] = given_array[i] helper(given_array,subset,i+1) all_subsets([1,2])
class Solution: # @param A, a list of integers # @param target, an integer to be inserted # @return integer def searchInsert(self, A, target): left, right = 0, len(A)-1 while left<=right: if A[left]>target: return left elif A[right]<target: return right+1 else: mid = (left+right)//2 if A[mid]==target: return mid elif A[mid]>target: right = mid-1 else: left = mid+1
# Definition for a point # class Point: # def __init__(self, a=0, b=0): # self.x = a # self.y = b class Solution: # @param points, a list of Points # @return an integer def maxPoints(self, points): maxNum=0 for i in range(len(points)): map, same, inf, maxCurr, start={}, 1, 0, 0, points[i] for j in range(i+1,len(points)): end=points[j] if start.x==end.x and start.y==end.y: same+=1 elif start.x==end.x: inf+=1 else: slope=float(end.y-start.y)/(end.x-start.x) if slope not in map: map[slope]=1 else: map[slope]+=1 for slope in map: maxCurr=max(map[slope]+same, maxCurr) maxNum=max(maxNum, inf+same, maxCurr) return maxNum
"""This module contains examples of stream_func where f_type is 'element' and stream_func has a list of multiple input streams, a single output stream, and the operation is stateless. These examples must have a LIST of input streams and not a single input stream. The functions on static Python data structures are of the form: list -> element """ if __name__ == '__main__': if __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from functools import partial from Stream import Stream, _no_value from Operators import stream_func import numpy as np def main(): # Functions: list, state -> list, state delta = 0.5 def inrange_and_outlier(x_and_y_lists, state): a, b, n, x_sum, y_sum, xx_sum, xy_sum = state x_array, y_array = np.array(x_and_y_lists) l = len(x_array) if not l: return (x_and_y_lists, state) n_array = np.arange(n, n+l,1) x_sum_array = x_sum + np.cumsum(x_array) y_sum_array = y_sum + np.cumsum(y_array) xy_sum_array = xy_sum + np.cumsum(x_array*y_array) xx_sum_array = xx_sum + np.cumsum(x_array*x_array) a_array = ((xy_sum_array - x_sum_array*y_sum_array/np.rint(n_array))/ (xx_sum_array - x_sum_array*x_sum_array/np.rint(n_array))) b_array = y_sum_array/np.rint(n_array) - a*x_sum_array/np.rint(n_array) z_list = zip(*x_and_y_lists) outliers = np.where(abs(a_array*x_array + b_array - y_array) > delta*abs(y_array)) inrange = np.where(abs(a_array*x_array + b_array - y_array) <= delta*abs(y_array)) outliers_array = np.hstack([x_array[outliers], y_array[outliers]]) #outliers_array = np.array([x_array[outliers], y_array[outliers]]) inrange_array = np.array([x_array[inrange], y_array[inrange]]) #return_array = np.array([inrange_array, outliers_array]) state = (a_array[-1], b_array[-1], n_array[-1], x_sum_array[-1], y_sum_array[-1], xx_sum_array[-1], xy_sum_array[-1]) return ([inrange_array, outliers_array], state) # Functions: stream -> stream. # The n-th element of the output stream is f() applied to the n-th # elements of each of the input streams. # Function mean is defined above, and functions sum and max are the # standard Python functions. # state = a, b, n, x_sum, y_sum, xx_sum, xy_sum # xx_sum is set to a small value to avoid division by 0.0 # n is set to 2 to reflect that the regression is assumed to have # been running for at least 2 points. state=(1.0, 0.0, 2, 0.0, 0.0, 0.001, 0.0) inrange_and_outlier_streams = partial(stream_func, f_type='list', f=inrange_and_outlier, num_outputs=2, state=state) # Create stream x, and give it name 'x'. x = Stream('input_0') y = Stream('input_1') inrange_stream, outlier_stream = inrange_and_outlier_streams([x,y]) # Give names to streams u, v, and w. This is helpful in reading output. inrange_stream.set_name('inrange') outlier_stream.set_name('outlier') print # Add values to the tail of stream x. x.extend(range(10, 15, 1)) y.extend(range(10, 15, 1)) # Print recent values of the streams print 'recent values of input streams' x.print_recent() y.print_recent() print 'recent values of output streams' inrange_stream.print_recent() outlier_stream.print_recent() print print 'Adding [15, 16, ...19], [150, 160,..190] to 2 streams.' # Add more values to the tail of stream x. x_list = range(15, 20, 1) y_list = [10*v for v in x_list] x.extend(x_list) y.extend(y_list) # Print recent values of the streams print 'recent values of input streams' x.print_recent() y.print_recent() print 'recent values of output streams' inrange_stream.print_recent() outlier_stream.print_recent() print print 'The regression parameters take some time to adjust' print 'to the new slope. Initially x = y, then x = 10*y' if __name__ == '__main__': main()
"""This module contains examples of stream_func where f_type is 'element' and stream_func has a list of multiple input streams, a single output stream, and the operation is stateless. These examples must have a LIST of input streams and not a single input stream. The functions on static Python data structures are of the form: list -> element """ if __name__ == '__main__': if __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from functools import partial from Stream import Stream, _no_value from Operators import stream_func def main(): def inrange_and_outlier_streams_adaptive( xy_streams, delta): def inrange_and_outlier(x_and_y, state): x, y = x_and_y a, b, n, x_sum, y_sum, xx_sum, xy_sum = state # Compute output if abs(a*x + b - y) > delta: # (x,y) is an outlier. # The streams returned by stream func are: # [inrange stream outlier stream] # Return _no_value for the inrange stream. return_list = [_no_value, x_and_y] else: # (x,y) is inrange. # Return _no_value for the outlier stream. return_list = [x_and_y, _no_value] # Compute the next state n += 1 x_sum += x y_sum += y xy_sum += x*y xx_sum += x*x a = (xy_sum - x_sum*y_sum/float(n))/(xx_sum - x_sum*x_sum/float(n)) b = y_sum/float(n) - a*x_sum/float(n) state = a, b, n, x_sum, y_sum, xx_sum, xy_sum return (return_list, state) # We assume here that an earlier computation was carried # out to fit a straight line over 2 points (0.0, 0.0) and # (1.0, 1.0). This prior computation is not shown here. # So, n, x_sum, y_sum, xx_sum, xy_sum are # 2, 1.0, 1.0, 1.0, 1.0, respectively. initial_state = (1.0, 0.0, 2, 1.0, 1.0, 1.0, 1.0) return stream_func( inputs=xy_streams, f_type='element', f=inrange_and_outlier, num_outputs=2, state=initial_state) # Create streams x and y, and give it # names 'input_0', 'input_1' x = Stream('input_0') y = Stream('input_1') # Create streams inrange_stream, outlier_stream inrange_stream, outlier_stream = \ inrange_and_outlier_streams_adaptive(xy_streams=[x,y], delta=0.5) # Give names to inrange_stream, outlier_stream. # This is helpful in reading output. inrange_stream.set_name('inrange') outlier_stream.set_name('outlier') print # Add values to the tail of streams x and y. x.extend(range(10, 15, 1)) y.extend(range(10, 15, 1)) # Print recent values of the streams print print 'Recent values of input streams' x.print_recent() y.print_recent() print print 'Recent values of output streams' inrange_stream.print_recent() outlier_stream.print_recent() print print 'Adding [15, 16, ...19], [16, 7,..20] to x and y streams.' # Add more values to the tail of stream x. x.extend(range(15, 25, 1)) y.extend(range(16, 26, 1)) # Print recent values of the streams print print 'Recent values of input streams' x.print_recent() y.print_recent() print print 'Recent values of output streams' inrange_stream.print_recent() outlier_stream.print_recent() print print 'The regression parameters take some time to adjust' print 'to the new slope. Initially x = y, then x = y+1' if __name__ == '__main__': main()
"""This module contains examples of stream_func where f_type is 'element' and stream_func has a single input stream, a single output stream, and the operation is stateless. The functions on static Python data structures are of the form: element -> element """ if __name__ == '__main__': if __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from functools import partial from Stream import Stream, _no_value from Operators import stream_func def main(): # Functions: element -> element def square(v): return v*v def double(v): return 2*v def even(v): if not v%2: return v else: return _no_value def multiply_elements_in_stream(stream, multiplier): def mult(v): return multiplier*v return stream_func(inputs=stream, f_type='element', f=mult, num_outputs=1) def square_elements_in_stream(stream): return stream_func(stream, f_type='element', f=square, num_outputs=1) # Functions: stream -> stream. # Each element of the output stream is f() applied to the corresponding # element of the input stream. stream_square = partial(stream_func, f_type='element', f=square, num_outputs=1) stream_double = partial(stream_func, f_type='element', f=double, num_outputs=1) stream_even = partial(stream_func, f_type='element', f=even, num_outputs=1) # Create stream x, and give it name 'x'. x = Stream('input') # u is the stream returned by stream_square(x) and # v is the stream returned by stream_double(x) # w is the stream returned by stream_square(v) and # so w could have been defined as: # stream_square(stream_double(x)) # a is the stream containing only even values of x # Function even(v) may return _no_value, but # _no_value is not inserted into the stream. # Thus even(v) acts like a filter. r = square_elements_in_stream(x) u = stream_square(x) v = stream_double(x) w = stream_square(v) a = stream_even(x) b = multiply_elements_in_stream(stream=x, multiplier=3) # Give names to streams u, v, and w. This is helpful in reading output. r.set_name('square of input') u.set_name('square of input') v.set_name('double of input') w.set_name('square of double of input') a.set_name('even values in input') b.set_name('multiply values in input') print print 'add [3, 5] to the tail of the input stream' # Add values to the tail of stream x. x.extend([3, 5]) # Print the N most recent values of streams x, u, v, w. x.print_recent() r.print_recent() u.print_recent() v.print_recent() w.print_recent() a.print_recent() b.print_recent() print print 'add [2, 6] to the tail of the input stream' # Add more values to the tail of stream x. x.extend([2, 6]) # Print the N most recent values of streams x, u, v, w. x.print_recent() r.print_recent() u.print_recent() v.print_recent() w.print_recent() a.print_recent() b.print_recent() if __name__ == '__main__': main()
"""This module contains examples of stream_func where f_type is 'element' and stream_func has a single input stream, a single output stream, and the operation is stateless. The functions on static Python data structures are of the form: element -> element """ if __name__ == '__main__': if __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from functools import partial from Stream import Stream, StreamArray, _no_value from Operators import stream_func import numpy as np def main(): # Functions: list, state -> list, state def cumulative(a, state): b = np.zeros(len(a)+1) b[0] = state b[1:] = a b = np.cumsum(b) return (b[1:], b[-1]) def average(a, state): n, cum = state b = np.zeros(len(a)+1) b[0] = cum b[1:] = a b = np.cumsum(b) n_array = np.arange(n, n+len(b), 1) c = b[1:]/np.rint(n_array[1:]) state = (n_array[-1], b[-1]) return (c, state) initial_cumulative = 10 stream_cumulative = partial(stream_func, f_type='list', f=cumulative, num_outputs=1, state=initial_cumulative) stream_average = partial(stream_func, f_type='list', f=average, num_outputs=1, state=(0,0.0)) # Create stream x and give it names 'x'. x = StreamArray('input') # v is the stream returned by stream_cumulative(x) and v = stream_cumulative(x) # avg is the stream returned by stream_average(x) avg = stream_average(x) # Give names to streams. This is helpful in reading output. v.set_name('cumulative sum of input starting at {0}'.format(initial_cumulative)) avg.set_name('average of input') print print 'add values [3, 5, 10] to the tail of the input stream.' # Add values to the tail of stream x. x.extend([3, 5, 10]) # Print the N most recent values of streams x, v, w. x.print_recent() v.print_recent() avg.print_recent() print print 'add values [2, 5, 11] to the tail of the input stream.' # Add more values to the tail of stream x. x.extend([2, 5, 11]) # Print the N most recent values of streams x, v, w. x.print_recent() v.print_recent() avg.print_recent() if __name__ == '__main__': main()
#!/usr/bin/python3 print("different functions of cat command") print("""1) for show the content of file : 2) for cat file1 > file2 : 3) for cat file1 >> file2 : 4) for display $ at the end of every line {cat -E}: """) ch=int(input("enter your choice")) if ch == 1: first=input("enter file name") con=open(first,"r") print(con.read()) con.close() if ch == 2: first=input("enter source file name") con=open(first,"r") second=input("enter second file name") con1=open(second,"w") con1.write(con.read()) con.close() con1.close() if ch == 3: first=input("enter source file name") con=open(first,"r") second=input("enter second file name") con1=open(second,"a+") con1.write(con.read()) con.close() con1.close() if ch == 4: first=input("enter file name") con=open("try1.txt","r") line=con.readline() while line: print(line+"$") line=con.readline() con.close()
## all funciton will take a list of integers as input def rsum(ints): if len(ints) == 1: return ints[0] else: return ints[0] + rsum(ints[1:]) def rmax(list): if len(list) == 1: return list[0] else: m = rmax(list[1:]) return m if m > list[0] else list[0] def second_smallest(int_list): if(len(int_list) == 2): if (int_list[0] >= int_list[1]): return (int_list[0],int_list[1]) else: return (int_list[1],int_list[0]) else: first_second_smallest,second_second_smallest = second_smallest(int_list[1:]) current_elem = int_list[0] if(second_second_smallest <= current_elem): return (second_second_smallest,current_elem) else: if (current_elem<=first_second_smallest): return (current_elem,first_second_smallest) else: return (first_second_smallest,second_second_smallest) def sum_max_min(ints): pass list_int = [1, 4, 6, 65, 7, 34, 23, 2] # print(rsum(list_int)) # print(rmax(list_int)) # print(second_smallest(list_int))
# Functions for reading tables and databases import glob from database import * # a table is a dict of {str:list of str}. # The keys are column names and the values are the values # in the column, from top row to bottom row. # A database is a dict of {str:table}, # where the keys are table names and values are the tables. # YOU DON'T NEED TO KEEP THE FOLLOWING CODE IN YOUR OWN SUBMISSION # IT IS JUST HERE TO DEMONSTRATE HOW THE glob CLASS WORKS. IN FACT # YOU SHOULD DELETE THE PRINT STATEMENT BEFORE SUBMITTING file_list = glob.glob('*.csv') # print(file_list) # Write the read_table and read_database functions below def read_table(table_file): '''(str) -> Table Return a Table with a given table_file. ''' open_file = open(table_file, "r") # convert file to list of strings table_list = open_file.readlines() columns = table_list[0].strip().split(",") table_data = {} # populate table_data with first line of file for key in columns: table_data[key] = [] # loop rest of the data for data in table_list[1:]: data_list = data.strip().split(",") # use index to get corresponding key and value for i in range(len(columns)): key = columns[i] value = data_list[i].strip() table_data[key].append(value) new_table = Table() new_table.populate_table(table_data) return new_table def read_database(): '''() -> Database Return a Database with a list of file name in the current directory. ''' database_data = {} for table_file in file_list: # get name of file as key file_name = table_file.split(".")[0] table = read_table(table_file) database_data[file_name] = table new_database = Database() new_database.populate_database(database_data) return new_database
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Funcion de lectura de archivos de Tablero # # @param num = numero de archivo a leer #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ listaIndices = [] def read_file(Board, num): #Abre el archivo y lo lee, si no lo encuentra devuelve un mensaje y cierra el programa try: with open('Table_gen/TableroDoble'+str(num)+'.txt') as tdFile: lines = tdFile.readlines() for i in range(len(lines)): lines[i] = lines[i].replace("\n","") except: print('No se encontro el tablero') return #inserta los valores del tablero del archivo en una matriz para poder utilizarla posteriormente for line in lines[2:]: if line == '': break holder = [] for item in (line.split(" ")[:-1]): holder.append(int(item)) Board.append(holder) return #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Funcion para verificar si una ficha se encuentra en la lista de fichas, prueba # ambas posiciones [1|0] y [0|1] # # @param pPair = Ficha por verificar # @param pList = Lista de fichas donde se busca la ficha a verificar #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def verify(pPair, pList): if(pPair in pList): return True else: swap(pPair) return pPair in pList def swap(pPair): pPair[0], pPair[1] = pPair[1], pPair[0] return #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Funcion generadora de soluciones para algoritmo de fuerza bruta # # @param num = Cantidad de digitos de la posible solucion #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def solucion_gen(num): solution = [] for i in range(num): solution.append(0) return solution def binary_increment(bin): for i in range(1,len(bin)+1): if(bin[-i]) == 0: bin[-i] = 1 return else: bin[-i] = 0 return #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def listToInt(lista): strings = [str(integer) for integer in lista] a_string = "".join(strings) an_integer = int(a_string) return an_integer def binlistToInt(binary): number = 0 for b in binary: number = (2 * number) + b return number def reductorListas(sol,pre): newSol=[] if (len(pre)<=len(sol)): for i in range(0,len(pre)): newSol.append(sol[i]) return newSol else: return sol def busquedaBinaria(unaLista, item): primero = 0 ultimo = len(unaLista)-1 encontrado = False while primero<=ultimo and not encontrado: puntoMedio = (primero + ultimo)//2 if unaLista[puntoMedio] == item: encontrado = True else: if item < unaLista[puntoMedio]: ultimo = puntoMedio-1 else: primero = puntoMedio+1 return encontrado def dominosaArr(size, array): filas = [] matriz = [] while (True): for i in range(0, size + 2): filas.append(array[i]) matriz.append(filas) del array[:size + 2] filas = [] if len(array) < (size + 2): break return matriz # Pasa un array comun a un una matriz ordenada para el BOARD def dominosaArr(size, array): filas = [] matriz = [] while (True): for i in range(0, size + 2): filas.append(array[i]) matriz.append(filas) del array[:size + 2] filas = [] if len(array) < (size + 2): break return matriz #Pasa una lista de char a int def charToIntList(word): newList = [char for char in word] ''.join(newList) newList = [int(integer) for integer in newList] return newList def generarTabla(n): global listaIndices total = (n-1)*(n+2) for i in range(0,total): listaIndices += [False] return listaIndices def genIndexList(size): row = size+2 column = size+1 row_list=[] matrix=[] while(True): for i in range(row): row_list.append(False) matrix.append(row_list) row_list=[] if len(matrix)==column: break return matrix def solutionBoard(sol,board,size): while (len(sol)!=0): for i in range(size+1): for j in range (size+2): if (board[i][j]==False) and (sol[0]==0): board[i][j]="R" board[i][j+1]="L" del sol[0] elif (board[i][j]==False) and (sol[0]==1): board[i][j]="D" board[i+1][j]="U" del sol[0] #print(board) return board
import unittest # this version does not keep the order def deduplicate_v1(duplicated_list): return list(set(duplicated_list)) # my first approach for keeping the order. Complexity O(n ^ 2) def deduplicate_v2(duplicated_list): result = list() for element in duplicated_list: if element not in result: # this implies another loop result.append(element) return list(result) # Complexity O(n) def deduplicate_v3(duplicated_list): deduplicated_dict = dict() result = list() for element in duplicated_list: if not deduplicated_dict.get(element, False): deduplicated_dict[element] = True result.append(element) return result class TestDeduplicate(unittest.TestCase): def test_list_without_duplicated_elements(self): self.assertEqual(deduplicate_v1([1, 2]), [1, 2]) def test_list_with_sorted_duplicated_elements(self): self.assertEqual(deduplicate_v1([1, 1, 2, 2, 3]), [1, 2, 3]) def test_list_with_unsorted_duplicated_elements(self): self.assertEqual(deduplicate_v3([2, 2, 1, 1, 1, 3]), [2, 1, 3]) unittest.main(exit=False)
#assignment #assume that i have a list, inside a list we have show how many times a number exist in a list. name=['aman', 'preet', 'aman', 'preet', 'deep', 'aman', 'deep', 'deep', 'deep', 'aman', 'aman'] print(name) print(type(name)) #to print aman print("the name aman is founded in a given list",name.count("aman"),"times") #to print deep print("the name deep is founded in a given list",name.count("deep"),"times") #to print preet print("the name preet is founded in a given list",name.count("preet"),"times")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # transform string to datetime import datetime string = '2017/09/26 11:39:00' d = '2017-09-26' str2datetime = datetime.datetime.strptime(string, '%Y/%m/%d %H:%M:%S').date() str2date1 = datetime.datetime.strptime(d, '%Y-%m-%d') str2date2 = datetime.datetime.strptime(d, '%Y-%m-%d').date() print(str2datetime) print(str2date1) print(str2date2) # list 类型 lst = [1, 2, 3, 'a', 'b', 'c', '2017-09-26 00:00:00'] print(lst[0]) print(lst[0:2]) print(lst[:4]) print(lst[3:]) print(lst[::-1]) # 翻转list # 增加 lst.append('xw'); print(lst) lst.insert(5, 'm'); print(lst) lst.extend(['2222', '33333']) # 末尾插入多个元素,以list格式呈现 print(lst) # lst.copy() # lst.pop() 从末尾或者是指定的位置删除字典的值 # lst.remove() 移除指定的值 # lst.clear() 清除指定的值 # del lst 删除整个list ''' 修改 ''' lst = [1, 2, 3, 'a', 'b', 'c', '2017-09-26 00:00:00'] lst[2] = '可惜我不是水平座' print(lst) lst[3:4] = ['大城小事', '野孩子'] print(lst) ''' 其他的方法 ''' lst = ['b', 2, '可惜我不是水平座', '大城小事', '野孩子', 'b', 'c', '2017-09-26 00:00:00'] print(lst.count('b')) # 计数的方法 print(lst.index('c')) # 如果有多个相同的元素,会返回第一个元素 # lst.reverse() # 反转函数 lst = [1, 2, 3, 6, 3, 2] lst.sort(reverse=False) # 排序reverse = True为降序 print(lst)
""" Movie Class Creates a movie object with a youtube trailer, poster art and title """ class Movie(object): def __init__(self, title, poster_image_url, trailer_youtube_url): """ Movie constructor Parameters ---------- title : string title of the movie poster_image_url : string image of the poster art for the movie trailer_youtube_url : string youtube url """ self.trailer_youtube_url = trailer_youtube_url self.poster_image_url = poster_image_url self.title = title
import random import charSet as cs class Word_Based_Password: def __init__(self): self.password = "PROMPT: Select options!" def randomize_case(self, letter): if letter == " ": letter = "" elif letter != " ": randomChoice = random.choice('abc') if randomChoice == 'a': letter = letter.lower() elif randomChoice == 'b': letter = letter.upper() elif randomChoice == 'c': letter = letter return letter def find_lookalike(self, letter): if letter.upper() in cs.specialsDict: letter = (random.choice(cs.specialsDict[letter.upper()])) return letter else: return('ERROR: Your word should only consist of letters.') def mix_chars_and_case(self, customWord, n): wordWithRandomCase = ''.join(self.randomize_case(letter) for letter in customWord) wordAsList = list(wordWithRandomCase) indexToChange = random.sample(range(0, len(customWord)), int(n)) for indexNumber in indexToChange: x = indexNumber letterToSubstitute = customWord[x] letterAsNewCharacter = self.find_lookalike(letterToSubstitute) wordAsList[x] = letterAsNewCharacter mixedCaseAndSpecials = ''.join(wordAsList) return mixedCaseAndSpecials def add_new_characters(self, customWord, n, chosenSet): wordAsList = list(customWord) for i in range(int(n)): randomSymbol = random.choice(chosenSet) randomIndex = random.randint(0, len(customWord)) wordAsList.insert(randomIndex, randomSymbol) i += 1 return (''.join(wordAsList)) def generate_word_based_password(self, theWord, choicesLevel1, numberMixChange=2, numberAddSigns=3, choicesLevel2=[1, 0, 0]): self.theWord = theWord # the word the user has entered self.choicesLevel1 = choicesLevel1 # choice from the radiobuttons - value 1, 2, 3 or 4 self.numberMixChange = numberMixChange # under Radiobutton No. 3, "How many letters do you want # to have changed to specials or numbers?" self.choicesLevel2 = choicesLevel2 # choice from the checkboxes under radiobutton No.4 self.numberAddSigns = numberAddSigns # under Radiobutton No. 4, "How many signs do you want to add?" self.randomized = ''.join(self.randomize_case(sign) for sign in self.theWord) if self.choicesLevel1 == 1: # Mix case randomly self.password = self.randomized elif self.choicesLevel1 == 2: # Change all the letters to look-alike\nnumbers and special characters self.password = "".join(self.find_lookalike(sign) for sign in self.theWord) elif self.choicesLevel1 == 3: # Mix case and change a chosen number of letters to special # characters and/or numbers # self.wordWithRandomCase = "".join(self.find_lookalike(sign) for sign in self.theWord) if int(self.numberMixChange) > int(len(theWord)): # if the number of chars to be changed exceeds the number self.password = "PROMPT: Choose a lower number!" # of chars in theWord, display a prompt. else: self.password = self.mix_chars_and_case(self.theWord, self.numberMixChange) elif self.choicesLevel1 == 4: # Add a chosen number of special characters and/or numbers in between the word's letters if choicesLevel2 == [1, 0, 0]: # NUMBERS: usersChoices = cs.numbers self.password = self.add_new_characters(self.theWord, self.numberAddSigns, usersChoices) elif choicesLevel2 == [0, 1, 0]: # SPECIALS usersChoices = cs.specialChars self.password = self.add_new_characters(self.theWord, self.numberAddSigns, usersChoices) elif choicesLevel2 == [1, 1, 0]: # NUMBERS AND/OR SPECIALS usersChoices = cs.specialChars + cs.numbers self.password = self.add_new_characters(self.theWord, self.numberAddSigns, usersChoices) elif choicesLevel2 == [1, 0, 1]: # NUMBERS + MIXED CASE usersChoices = cs.numbers self.password = self.add_new_characters(self.randomized, self.numberAddSigns, usersChoices) elif choicesLevel2 == [0, 1, 1]: # SPECIALS + MIXED CASE usersChoices = cs.specialChars self.password = self.add_new_characters(self.randomized, self.numberAddSigns, usersChoices) elif choicesLevel2 == [0, 0, 1]: # MIXED CASE self.password = self.randomized elif choicesLevel2 == [1, 1, 1]: # MIXED CASE, NUMBERS AND SPECIALS usersChoices = cs.specialChars + cs.numbers self.password = self.add_new_characters(self.randomized, self.numberAddSigns, usersChoices) else: # no checkbox checked self.password = "PROMPT: Choose your options!" return self.password
class Value_Action(): # GET VALUE def get_value(self, value, whereFrom): value = whereFrom.get() return value # +/- BUTTON METHODS def increment(self, value, place): value = self.get_value(value, place) value = int(value) value += 1 value = str(value) place.delete(0, 'end') place.insert(0, value) def decrement(self, value, place): value = self.get_value(value, place) value = int(value) if value > 0: value -= 1 else: value = 0 value = str(value) place.delete(0, 'end') place.insert(0, value)
#add 5 6 and 7 to the Tuple my_tuple = (1,2,3) my_tuple = my_tuple[:3] + (5,6,7) print(my_tuple)
import pandas as pd from sklearn import preprocessing import numpy as np history_days = 30 # Predict a month into future def csv_to_dataset(csv_file_path): file_data = pd.read_csv(csv_file_path) file_data = file_data.iloc[::-1] # Reverse order, most recent values last, want to be predicting into future, not past file_data = file_data.drop('date', axis=1) file_data = file_data.drop(0, axis=0) print("File data DataFrame:", file_data.shape) print(file_data.head()) file_data = file_data.values normalizing_scaler = preprocessing.MinMaxScaler() normalized_data = normalizing_scaler.fit_transform(file_data) print() print("Normalized data") print(normalized_data[0:5,:]) # Data is in order of: Open stock value, high value, low, close, and volume - ohlcv # Creates array of 5x50-value array windows, each one will be a training input into model ohlcv_histories_normalised = np.array([normalized_data[i : i + history_days].copy() for i in range(len(normalized_data) - history_days)]) print() print("Normalized inputs", ohlcv_histories_normalised.shape) #print(ohlcv_histories_normalised[0:2,0:5]) # Get scaled stock open price values, which model is predicting next_day_open_values_normalised = np.array([normalized_data[:,0][i + history_days].copy() for i in range(len(normalized_data) - history_days)]) next_day_open_values_normalised = np.expand_dims(next_day_open_values_normalised, -1) #print() print("Next day open values scaled:", next_day_open_values_normalised.shape) # Get unscaled stock open price from original file data next_day_open_values = np.array([file_data[:,0][i + history_days].copy() for i in range(len(file_data) - history_days)]) next_day_open_values = np.expand_dims(next_day_open_values, -1) print("Next day open values unscaled:", next_day_open_values.shape) y_normaliser = preprocessing.MinMaxScaler() y_normaliser.fit(next_day_open_values) # Moving average technical indicator of stock price input moving_averages = [] for his in ohlcv_histories_normalised: sma = np.mean(his[:,3]) # Using closing price of the stocks for the moving average, not open price moving_averages.append(np.array([sma])) moving_averages = np.array(moving_averages) # Convert to numpy array moving_averages_scaler = preprocessing.MinMaxScaler() # Scale with min-max scaler moving_averages_normalised = moving_averages_scaler.fit_transform(moving_averages) assert ohlcv_histories_normalised.shape[0] == next_day_open_values_normalised.shape[0] == moving_averages_normalised.shape[0] return ohlcv_histories_normalised, next_day_open_values_normalised, next_day_open_values, y_normaliser #return ohlcv_histories_normalised, moving_averages_normalised, next_day_open_values_normalised, next_day_open_values, y_normaliser def multiple_csv_to_dataset(test_set_name): import os ohlcv_histories = 0 moving_averages = 0 next_day_open_values = 0 # For each company stock dataset in directory, add data to training dataset for csv_file_path in list(filter(lambda x: x.endswith('daily.csv'), os.listdir('./'))): if not csv_file_path == test_set_name: print(csv_file_path) if type(ohlcv_histories) == int: ohlcv_histories, moving_averages, next_day_open_values, _, _ = csv_to_dataset(csv_file_path) else: a, b, c, _, _ = csv_to_dataset(csv_file_path) ohlcv_histories = np.concatenate((ohlcv_histories, a), 0) moving_averages = np.concatenate((moving_averages, b), 0) next_day_open_values = np.concatenate((next_day_open_values, c), 0) ohlcv_train = ohlcv_histories mov_avg_train = moving_averages open_prices_train = next_day_open_values ohlcv_test, mov_avg_test, open_prices_test, unscaled_open_prices_test, y_normaliser = csv_to_dataset(test_set_name) return ohlcv_train, mov_avg_train, open_prices_train, ohlcv_test, mov_avg_test, open_prices_test, unscaled_open_prices_test, y_normaliser
''' working exercise from sentex tutorials. with mods for clarification + api doc references. How to program the Best Fit Line - Practical Machine Learning Tutorial with Python p.9 https://youtu.be/KLGfMGsgP34?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v linear regression model y=mx+b m = mean(x).mean(y) - mean (x.y) ------------------------------ (mean(x)^2 - mean(x^2) b = mean(y) - m . mean(x) ''' from statistics import mean import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use('fivethirtyeight') xs = [1,2,3,4,5,6] ys = [5,4,6,5,6,7] #plt.scatter(xs, ys) #plt.show() xs = np.array([1,2,3,4,5,6], dtype=np.float64) ys = np.array([5,4,6,5,6,7], dtype=np.float64) def best_fit_slope_and_intercept(xs, ys): m = (mean(xs) * mean(ys) - mean(xs*ys)) / ( mean(xs)*mean(xs) - mean(xs*xs) ) b = mean(ys) - m * mean(xs) return m, b m,b = best_fit_slope_and_intercept(xs, ys) #regression_line = xs*m+b regression_line = [m*x+b for x in xs] print ( "m={}".format(m), ", b={}".format(b) ) predict_x = 8 predict_y = (m*predict_x) + b plt.scatter(xs, ys) plt.scatter(predict_x, predict_y, color = 'g', marker='s', s=50) #plt.plot(xs, xs*m+b) plt.plot(xs, regression_line) plt.xlabel('xs') plt.ylabel('ys') plt.title("plot mx+b using linear regression fit") plt.show() ''' http://matplotlib.org/examples/style_sheets/plot_fivethirtyeight.html '''
import csv # Write file. with open('file.csv', 'w', newline='') as csvfile: csv_writer = csv.writer(csvfile, delimiter=';') csv_writer.writerow(['titile1', 'titile2', 'titile3', 'titile4', 'titile5']) csv_writer.writerow(['column1', 'column2', 'column3', 'column4', 'column5']) # Read file. with open('file.csv', 'r', newline='') as csvfile: csv_reader = csv.reader(csvfile, delimiter=';') for line in csv_reader: print(';'.join(line)) # Read to Dict with open('file.csv', 'r', newline='') as csvfile: csv_reader = csv.DictReader(csvfile, delimiter=';') for row in csv_reader: print(row) # Write to Dict with open('file.csv', 'w', newline='') as csvfile: fieldnames = ['title1', 'title2', 'title3', 'title4', 'title5'] csv_writer = csv.DictWriter(csvfile, delimiter=';' ,fieldnames=fieldnames) dict_model = {'title1':'column1', 'title2':'column2', 'title3':'column3', 'title4':'column4', 'title5':'column5'} csv_writer.writeheader() csv_writer.writerow(dict_model)
""" A text based clone of 2048 Made by Chendi """ import random import utils import enum import collections # because typos CURRENT_GAME = "current game" class Cell: """represents a cell in a board""" def __init__(self, value=0): self.length = 1 self.value = value self.has_merged = False class Board: """represents a board for 2048""" def __init__(self, mode): self.size = mode.size self.number_of_cells = self.size ** 2 self.cells = [Cell() for _ in range(self.number_of_cells)] def move_blocks(self, x, positive, game): """Moves all blocks in the board""" # generates indexes of cell for each row/column for i in range(self.size): if x: indexes = list(range(i * self.size, (i + 1) * self.size)) else: indexes = list(range(i, self.number_of_cells, self.size)) if positive: indexes.reverse() self.move_line(indexes, game) def move_line(self, line, game): for j in line: current_cell = self.cells[j] current_cell.has_merged = False neighbor = self.cells[line[line.index(j) - 1]] if current_cell.value: while current_cell is not self.cells[line[0]]: # moves if neighbor is empty if not neighbor.value: neighbor.value = current_cell.value neighbor.has_merged = current_cell.has_merged current_cell.value = 0 j = line[line.index(j) - 1] current_cell = self.cells[j] neighbor = self.cells[line[line.index(j) - 1]] # merges blocks elif ( current_cell.value == neighbor.value and not current_cell.has_merged and not neighbor.has_merged ): current_cell.value += 1 game.score += game.mode().increase_score(current_cell.value) neighbor.value = 0 current_cell.has_merged = True else: break def check_can_move(self): """Checks if the player can move""" if self.number_of_empty_cells(): return True # checks if adjacent cells are the same for i in range(self.size): row_indexes = list(range(i * self.size, i * self.size + self.size)) column_indexes = list(range(i, self.number_of_cells, self.size)) for indexes in (row_indexes, column_indexes): for j in indexes: if j is indexes[0]: continue elif self.cells[j].value == self.cells[indexes[indexes.index(j) - 1]].value: return True return False def number_of_empty_cells(self): """Checks if the board is full and return number of empty spaces""" empty = 0 for cell in self.cells: if cell.value == 0: empty += 1 return empty def make_new_block(self, mode): """Makes random new block""" if not self.number_of_empty_cells(): return empty_blocks = [cell for cell in self.cells if cell.value == 0] empty_cell = random.choice(empty_blocks) value = 1 if random.randint(0, 10) == 10: value = 2 empty_cell.value = value def draw_board(self, game): """returns text representation of the board""" text = "" max_length = 0 for cell in self.cells: cell.length = len(str(game.mode().values[cell.value])) max_length = max(self.cells, key=lambda cell: cell.value).length for row in range(game.mode().size): for column in range(game.mode().size): cell = game.board.cells[row * game.mode().size + column] spaces = (max_length - cell.length + 1) * " " text += spaces * 2 + str(game.mode().values[cell.value]) text += "\n" return text @enum.unique class GameIncreaseModes(enum.Enum): TIMES_2 = enum.auto() PLUS_1 = enum.auto() RANDOM = enum.auto() class GameMode: """class to represent different gamemodes""" shuffled = [i for i in range(100)] random.shuffle(shuffled) def __init__( self, start_value=2, increase_type=GameIncreaseModes.TIMES_2, size=4, win_value=11, description="" ): self.size = size self.number_of_cells = size ** 2 self.increase_type = increase_type self.high_score = 0 if increase_type == GameIncreaseModes.RANDOM: self.values = [0] + GameMode.shuffled else: self.values = [0, start_value] for _ in range(self.number_of_cells + 2): self.values.append(self.increase(self.values[-1])) self.win_value = win_value self.description = description def name(self): return utils.get_key(Game.modes, self, is_same=False) def increase(self, value): """Increases cell value based on game mode""" if self.increase_type == GameIncreaseModes.TIMES_2: next_value = value * 2 elif self.increase_type == GameIncreaseModes.PLUS_1: next_value = value + 1 return next_value def increase_score(self, value): """increases score based on gamemode""" return 2 ** value Direction = collections.namedtuple("Direction", "commands x positive") @enum.unique class Directions(enum.Enum): UP = Direction(("up", "u", "^"), False, False) LEFT = Direction(("left", "l", "<"), True, False) DOWN = Direction(("down", "d", "v"), False, True) RIGHT = Direction(("right", "r", ">"), True, True) class Game: """class to represent each game of 2048""" modes = { "normal": GameMode(description="normal 2048"), "65536": GameMode(size=5, win_value=16, description="5x5 board"), str(2 ** 20): GameMode(size=6, win_value=20, description="6x6 board"), "eleven": GameMode( 1, GameIncreaseModes.PLUS_1, description="blocks increase by 1 when merging" ), "twenty": GameMode( 1, GameIncreaseModes.PLUS_1, size=5, win_value=20, description="eleven with a 5x5 board" ), "confusion": GameMode( 1, GameIncreaseModes.RANDOM, description="randomly generated block sequence" ) } game_commands = ["restart", "{direction}"] def __init__(self, name): self.name = name self.score = 0 self.mode_name = "normal" self.has_won = False self.board = Board(self.mode()) for _ in range(2): self.board.make_new_block(self.mode()) def mode(self): return self.modes[self.mode_name] def update(self): """returns text based on current state""" text = "" if self.check_win() and not self.has_won: # check has_won so it doesnt say the player won forever after they win self.has_won = True text += self.draw_game() text += "you won" elif not self.board.check_can_move(): text += "you lost, use restart to restart" text += "\n\n" text += self.draw_game() return text def draw_game(self): """returns string representation of the game""" text = utils.join_items( utils.description(self.name, self.mode().name(), newlines=0), f"score: {self.score}", newlines=2 ) text += self.board.draw_board(self) return text def restart(self, mode=None): """Resets the game""" self.mode_name = utils.default(mode, self.mode_name) self.score = 0 if self.mode_name == "confusion": self.setup_confusion() self.board = Board(self.mode()) for _ in range(2): self.board.make_new_block(self.mode()) self.has_won = False def move(self, x, positive): """Moves all blocks""" if (x, positive) == (None, None): return if self.board.check_can_move(): old_board_values = [cell.value for cell in self.board.cells] self.board.move_blocks(x, positive, self) # does not create new block if board is full or the board did not change if old_board_values != [cell.value for cell in self.board.cells]: self.board.make_new_block(self.mode()) def check_win(self): """checks if the player has won""" for block in self.board.cells: if block.value == self.mode().win_value: return True return False def setup_confusion(self): """shuffled the values for conffusion mode""" GameMode.shuffled.remove(0) random.shuffle(GameMode.shuffled) GameMode.shuffled.insert(0, 0) Game.modes["confusion"].values = GameMode.shuffled def play_game(self, commands): """runs the main game loop once""" text = "" command = next(commands) # check player movement for direction in Directions: direction = direction.value if command in direction.commands: self.move(direction.x, direction.positive) if self.score > self.mode().high_score: self.mode().high_score = self.score break else: if command in self.modes: if self.mode().size == self.modes[command].size: self.mode_name = command else: self.restart(command) elif command == "restart": self.restart() elif command != "": text += "invalid command, use help to see commands\n" text += self.update() return utils.newline(text)
nama = [] TL = [] nama = [item for item in input("Nama : ").split()] TL = [item for item in input("Tempat Tanggal Lahir : ").split()] jumlahKataNama = len(nama) - 1 jumlahkataTL = len(TL) -1 sisa_nama = "" for i in range(0,jumlahKataNama): sisa_nama = sisa_nama + nama[i] + " " tanggal = "" for i in range(jumlahkataTL-(jumlahkataTL-1),jumlahkataTL+1): tanggal = tanggal + TL[i] + " " print("Haloo!",nama[jumlahKataNama],",",sisa_nama) print("Anda lahir di",TL[0],"pada tanggal", tanggal)
import psycopg2 def connect_conn(): """Establish connection to database and return connection object.""" db = 'bgpuyxgj' user = 'bgpuyxgj' password = 'password' # Don't commit! host = 'raja.db.elephantsql.com' conn = psycopg2.connect(dbname=db, user=user, password=password, host=host) return conn def create_db(conn): """Add a database named titanic to repo. Creates types for: sex: 'male', 'female' and pclass: '1', '2', '3' """ create_enums = ''' CREATE TYPE sex AS ENUM ('male', 'female'); CREATE TYPE pclass AS ENUM ('1', '2', '3'); ''' curs = conn.cursor() curs.execute(create_enums) conn.commit() create_table = ''' DROP TABLE titanic; CREATE TABLE titanic ( id SERIAL PRIMARY KEY, survival BOOL, pclass pclass, name VARCHAR (255), sex sex, age FLOAT, sibsp INT, parch INT, fare FLOAT); ''' curs = conn.cursor() curs.execute(create_table) conn.commit() return conn def csv_to_db(file, conn): """Copy data from csv into new titanic database.""" curs = conn.cursor() with open(file) as f: lines = f.readlines()[1:] for line in lines: surv, pclass, name, sex, age, sibsp, parch, fare = line.split(',') curs.execute("INSERT INTO titanic (survival, pclass, name, sex, age, sibsp, parch, fare)\ VALUES (%s, %s, %s, %s, %s, %s, %s, %s);", (surv, str(pclass), str(name), sex, age, sibsp, parch, fare)) conn.commit() curr = conn.cursor() curr.execute('''SELECT * FROM titanic LIMIT 10''') print(f'Return from query: {curr.fetchall()}\nSuccess!!!') def query(conn, string: str): """Perform a query on titanic database and return result.""" curs = conn.cursor() curs.execute(f'{string}') result = curs.fetchall() return result def main(): conn = connect_conn() create_db(conn) csv_to_db('titanic.csv', conn) a = '''SELECT titanic.name FROM (SELECT t.name, t.survival FROM titanic t WHERE t.sex='male' and t.survival=FALSE) AS titanic''' print(query(conn, a)) if __name__ == "__main__": main()
# Q5:. A cryptarithmetic puzzle def Q5(): def isPZCZ(n): """Predicate to check that n, the input number, has the format PZCZ, i.e. the 2nd and 4th digits are equal. n: input number, assumed to be 4 digits Returns True if n has the format PZCZ, False otherwise.""" # convert to str x = str(n) # then we check if x[1] == x[3]: return True return False def isProductMUCHZ(pzcz, product): """Predicate to check that product has the format MUCHZ. pzcz: input number, assumed to be in format PZCZ product: input number More precisely, this predicate checks 3 things: (i) that product has exactly 5 digits (ii) that the last digit of product is Z, the last digit of pzcz (iii) that the 3rd digit of product is C, the 3rd digit of pzcz. Returns True if product passes all 3 checks, False otherwise.""" # convert to str p = str(product) n = str(pzcz) # then we check if len(p) == 5: if p[-1] == n[-1] and p[2] == n[2]: return True return False S = [(x,x*15) for x in range(1000,10000) if isPZCZ(x) and isProductMUCHZ(x,x*15)] print("-All solutions to the cryptarithmetic puzzle are:\n",S) Q5()
graph={ 1:[2,3], 2:[1,4,5,7], 3:[1,5,9], 4:[2,6], 5:[2,3,7,8], 6:[4], 7:[5,2], 8:[5], 9:[3], } def DFS(graph, root): visited = [] stack = [root] while stack: n = stack.pop() for i in graph[n]: if i not in visited: stack.append(i) if n not in visited: visited.append(n) return visited print(DFS(graph, 1))
#Given an array of integers, find the first missing positive integer #in linear time and constant space. In other words, #find the lowest positive integer that does not exist in the array. #The array can contain duplicates and negative numbers as well. #For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. #You can modify the input array in-place. input_list = [-2, 0, 2, 3] input_list.sort() # -1, 1, 3, 4 def lowest_positive_number(input_list): if input_list[-1] <= 0: return 1 for i in range(len(input_list) - 1): if input_list[i+1] - input_list[i] >= 2 and input_list[i+1] >= 0 and input_list[i] > -1: return input_list[i] + 1 return input_list[-1] + 1 nums = [-2, 0, 2, 3] def first_missing_positive(nums): s = set(nums) i = 1 while i in s: i += 1 return i print(lowest_positive_number(input_list)) print(first_missing_positive(nums))
##----------------------------------------------------------------- ##Real Python examples ##To check Using SMTP_SSL() ''' import smtplib,ssl smtp_server='smtp.gmail.com' port=465 sender='--Enter your email address--' password=input('Enter your password and press enter : ') context=ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server,port,context=context) as server: server.login(sender,password) ##print('It is working properly ') ''' ## To check Using TLS() connection ''' import smtplib,ssl smtp_server='smtp.gmail.com' port=587 sender='--Enter your email address--' password=input('Enter your password and press enter : ') context=ssl.create_default_context() with smtplib.SMTP(smtp_server,port) as server: server.ehlo() server.starttls(context=context) server.ehlo() server.login(sender,password) print('It is working properly ') ''' ##----------------------------------------------------------------- ##Send you plain text mails ##1.Using SSL ''' import smtplib,ssl smtp_server='smtp.gmail.com' port=465 sender='--Enter sender's email address--' reciever='--Enter reciever's email address--' password=input('Enter your password and press enter : ') message="""\ From:{} To:{} Subject:Hi There! This message is sent from Python! """.format(sender,reciever) context=ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server,port,context=context) as server: server.login(sender,password) server.sendmail(sender,reciever,message) ''' ##Using TLS ''' import smtplib,ssl smtp_server='smtp.gmail.com' reciever='--Enter reciever's email address--' port=587 sender='--Enter sender's email address--' reciever='--Enter reciever's email address--' password=input('Enter your password and press enter : ') message="""\ From:{} To:{} Subject:Hi There! This message is sent from Python! """.format(sender,reciever) context=ssl.create_default_context() with smtplib.SMTP(smtp_server,port) as server: server.ehlo() server.starttls(context=context) server.ehlo() server.login(sender,password) server.sendmail(sender,reciever,message) ''' ##----------------------------------------------------------------- ## Including HTML content ''' import smtplib,ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart smtp_server='smtp.gmail.com' port=465 sender=''--Enter sender's email address--' reciever='--Enter reciever's email address--' password=input('Enter your password and press enter : ') message=MIMEMultipart() message['Subject']='Email Automation' message['From']=sender message['To']=reciever text="""\ Hi, How are you? Hope everything is good!!""" html="""\ <html><body> <p>Hi, <br> How are you? Hope everything is good!!</p> </body></html> """ part1=MIMEText(text,'plain') part2=MIMEText(html,'html') message.attach(part1) message.attach(part2) context=ssl.create_default_context() msg=message.as_string() with smtplib.SMTP_SSL(smtp_server,port,context=context) as server: server.login(sender,password) server.sendmail(sender,reciever,msg) ''' ##----------------------------------------------------------------- ##Adding attachments using email package ''' import email,smtplib,ssl from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText smtp_server='smtp.gmail.com' port=465 subject='Email Automation using Python' body='This is an email with attachment sent from python' sender=''--Enter sender's email address--' reciever='--Enter reciever's email address--' password=input('Enter your password and press enter : ') message=MIMEMultipart() message['Subject']=subject message['From']=sender message['To']=reciever message['Bcc']=reciever message.attach(MIMEText(body,'plain')) filename='Resume.docx'##Add Resume.docx file in your project with open(filename,'rb') as f: part=MIMEBase('application','octet-stream') part.set_payload(f.read()) encoders.encode_base64(part) part.add_header( 'Content-Disposition', f"attachment; filename= {filename}",) message.attach(part) context=ssl.create_default_context() msg=message.as_string() with smtplib.SMTP_SSL(smtp_server,port,context=context) as server: server.login(sender,password) server.sendmail(sender,reciever,msg) ''' ##------------------------------------------------------------ ##To send mail to multiple users using excel file ''' import pandas as pd import smtplib,ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart smtp_server='smtp.gmail.com' port=587 sender='--Enter sender's email address--' password=input('Enter your password and press enter : ') message=MIMEMultipart() message['Subject']='Sending mails from excel sheet' message['From']=sender text="""\ Hi, How are you? Hope everything is good!! This mail is sent to the users read from excel sheet""" message.attach(MIMEText(text,'plain')) body=message.as_string() e=pd.read_excel('email.xlsx') emails=e['Emails'].values context=ssl.create_default_context() server=smtplib.SMTP(smtp_server,port) server.ehlo() server.starttls(context=context) server.ehlo() server.login(sender,password) for email in emails: server.sendmail(sender,email,body) server.quit() ''' ##------------------------------------------------------ ##To send mail to multiple users using csv file ''' import csv with open("contacts_file.csv") as file: reader = csv.reader(file) next(reader) # Skip header row for name, email, grade in reader: print(f"Sending email to {name}") # Send email here '''
from Tkinter import* root =Tk() frame1=Frame(root, width = 500, height = 400) frame1.pack() Label(frame1,text="Validador de Cedula", fg="Red", font=("Arial",18)).place(x=135,y=30) def is_valid_date(action, char, text): # Solo chequear cuando se añade un carácter. if action != "1": return True return char in "0123456789" and len(text) < 11 labela=StringVar() Label(frame1,text="Cedula", fg="Black", font=("Arial",18)).place(x=60,y=80) Label(frame1,text="Cedula Correcta", fg="Black", font=("Arial",18),textvariable=labela).place(x=60,y=300) validatecommand = root.register(is_valid_date) cedulavar=StringVar() Cedula = Entry(frame1,textvariable=cedulavar, text="Validador de Cedula", fg="Black", font=("Arial",18)).place(x=150,y=80) def onclic1(): c = 0 result = 0 p = 0 uj = 0 a = list(cedulavar.get()) b = [1,2,1,2,1,2,1,2,1,2] if len(a) < 11 : labela.set("Cedula Incorrecta") else : for i in range(10): c = int(a[i]) * b[i] if c >= 10 : d = list(str(c)) c = int(d[0]) + int(d[1]) result = result + c p = int(list(str(result))[0] + "0") uj = ( p / 10) * 10 if uj < result : result = (uj + 10) - result if result == int(a[10]) : labela.set("Cedula Correcta") else : labela.set("Cedula Incorrecta") print(result) boton1 = Button(frame1, text="Validar", command=onclic1).place(x=135,y=200) root.mainloop()
#coding=utf-8 class Solution: def quick_sort(self, lists, left, right): # 快速排序 if left >= right: return lists key = lists[left] low = left high = right print "before One iteration key:",key,lists while left < right: while left < right and lists[right] >= key: right -= 1 lists[left] = lists[right] print ("change left=right left:",left,"right:",right) while left < right and lists[left] <= key: left += 1 lists[right] = lists[left] print ("change right=left left:",left,"right:",right) lists[right] = key print ("after One iteration key:",key ,lists) print ("-----------------------") self.quick_sort(lists, low, left - 1) self.quick_sort(lists, left + 1, high) return lists def main(): s = Solution() arr = [49,38,65,97,76,13,27,49] print (s.quick_sort(arr,0,len(arr)-1)) if __name__ == '__main__': main()
#!/usr/bin/env python3 """Program to get internet IP info.""" import json import requests import argparse def getipinfo(website): """Get ip info from website.""" inforequest = requests.get(website) infobyte = inforequest.content return json.loads(infobyte) def printinfo(ipinfo): """Print out the Ip info.""" tabular = "{:<15} : {:<25}" print() print(tabular.format("IP", ipinfo['query'])) print(tabular.format("ISP", ipinfo['isp'])) print(tabular.format("City", ipinfo['city'])) print(tabular.format("Region", ipinfo['region'])) print(tabular.format("Country", ipinfo['country'])) print(tabular.format("Country Code", ipinfo['countryCode'])) print() def Main(): """Run if script is run.""" website = "http://ip-api.com/json/" parser = argparse.ArgumentParser() parser.add_argument("-i", "--ip", type=str, default="", help='IP other than localhosts IP', metavar="") args = parser.parse_args() website = website + args.ip ipinfo = getipinfo(website) printinfo(ipinfo) if __name__ == "__main__": Main()
#This is a basic script for practicing the syntax for different loops in python import sys class TestClass: i = 1 def __init__(self): self.i = 10000 def set_i(self, j): print(j) temp = self.i self.i = j print(temp) return(temp) if (len(sys.argv) < 2): argv = 1 else: argv = sys.argv[1] print(argv) #for loop using a restricted range for x in range(0,int(argv)): print("X Value: %d" % (x)) #For each loop throgh an array for y in [ 5, 10, 15]: print("Y value: %d" % (y)) #for loop with strings for f in ["TEST1", "TEST2", "TEST3", "TEST4", "TEST5"]: print(f.capitalize()) t = 0 while (t < 100): t += 1 if (t % 10 == 0): print(t) clsc = TestClass() clsc.set_i(100)
# Uses python3 import random def lcm_naive(a, b): for l in range(1, a*b + 1): if l % a == 0 and l % b == 0: return l return a*b def gcd(a, b): if b == 0: return a rem = a % b return gcd(b, rem) def lcm_fast(a, b): return int((a * b) / gcd(a, b)) def test_solution(): assert lcm_fast(6, 8) == 24 assert lcm_fast(761457, 614573) == 467970912861 for _ in range(20): a, b = random.randint(1,100), random.randint(1, 100) assert lcm_fast(a, b) == lcm_naive(a, b) if __name__ == '__main__': a, b = map(int, input().split()) print(lcm_fast(a, b)) #print(lcm_naive(a, b)) #test_solution()
def binary_tree_depth_order(tree: BinaryTreeNode) -> List[List[int]]: from collections import deque traversal = list() if tree is None: return traversal queue = deque() queue.append(tree) while queue: curr_level, queueSize = list(), len(queue) for i in range(queueSize): curr = queue.popleft() curr_level.append(curr.data) if curr.left: queue.append(curr.left) if curr.right: queue.append(curr.right) traversal.append(curr_level) return traversal
def multiply(num1, num2): result = [0] * (len(num1) + len(num2)) sign = -1 if (num1[0] < 0) ^ (num2[0] < 0) else 1 num1[0], num2[0] = abs(num1[0]), abs(num2[0]) for i in reversed(range(len(num2))): for j in reversed(range(len(num1))): result[i + j + 1] += num1[j] * num2[i] for i in reversed(range(1, len(result))): result[i - 1] += (result[i] // 10) result[i] %= 10 for i in range(len(result)): if result[i] != 0 or i == len(result) - 1: result[i] *= sign return result[i:] print(multiply([5,4,9,1], [7,3,0,2]))
def is_valid_sudoku(partial_assignment): #check 9 3x3 subgrids for rOffset in range(0, 7, 3): for cOffset in range(0, 7, 3): appeared = [False] * 9 for r in range(3): for c in range(3): num = partial_assignment[r + rOffset][c + cOffset] if num > 0: if appeared[num - 1]: return False else: appeared[num - 1] = True #check columns for c in range(9): appeared = [False] * 9 for r in range(9): num = partial_assignment[r][c] if num > 0: if appeared[num - 1]: return False else: appeared[num - 1] = True #check rows for r in range(9): appeared = [False] * 9 for c in range(9): num = partial_assignment[r][c] if num > 0: if appeared[num - 1]: return False else: appeared[num - 1] = True return True
def snake_string(s): lst = [] for i in range(1, len(s), 4): lst.append(s[i]) for i in range(0, len(s), 2): lst.append(s[i]) for i in range(3, len(s), 4): lst.append(s[i]) return ''.join(lst) print(snake_string("Hello World!"))
import os import random from hangman_art import logo,stages from hangman_words import word_list print(logo) chosen_word= random.choice(word_list) display = [] lives = 6 found = False for _ in chosen_word: display.append("-") print(display) while "".join(display) != chosen_word and lives >= 0: guess= input("Guess a letter: ").lower() _ = os.system('clear') for i in range(len(chosen_word)): if guess == chosen_word[i]: display[i] = chosen_word[i] found = True if found: found = False print(display) print(f"\n{guess} is the right letter.\n") else: print(stages[lives]) print(f"{guess} is not the right letter. You lose a life.\n") lives -= 1 if lives >= 0: print("\nYou won") else: print(f"\nYou lose. The right word was {chosen_word}")
import numpy as np # Create array manually a = np.array([0, 2, 4, 6]) # Get dimension of array print(a.ndim) #should print 1 ##### # Get shape of array print(a.shape) #should print (4,) meaning 4 dimensions on 0th axis # Get length of array print(len(a)) #should print 4 # Create multidimesional arrays manually b = np.array([[0, 1, 2], [3, 4, 5]]) b.ndim #should be 2, because its a matrix b.shape #should be (2, 3) because its a 2x3 matrix len(b) #should be 2 b/c the length of first dimension is 2 c = np.array([ [ [1,2], [3, 4], [5, 6] ] ]) print(c) print(c.ndim) #should 3 print(c.shape) #should be (1,3,2) b/c outer most array has only 1 nested array, and first nested array has 3 nested arrays, and 3 nested arrays have 2 elements, so 1x3x2 print(len(c)) #should be 1 d = np.array([ [ [1], [2] ], [ [3], [4] ] ]) print(d) print(d.ndim) #should be 3, b/c its a matrix of arrays print(d.shape) #should be (2, 2, 1) print(len(d)) #should be 2 #Creating arrays with functions a = np.arange(10) print(a) #creates array with values from 0-10, so 0-(n-1) b = np.arange(1, 9, 2) #syntax (start, not inclusive end, step size) print(b) #should print array([1, 3, 5, 7]) c = np.linspace(0, 1, 6) #syntax (start, end inclusive, number of elements in list) print(c) #should print array([0., 0.2, 0.4, 0.6, 0.8, 1.]) d = np.linspace(0, 1, 5, endpoint=False) #syntax (start, end not inclusive, numnber of elements, bool for inclusive end or not) print(d) #Common arrays a = np.zeros((3, 3)) #a 3x3 matrix of zeros print(a) b = np.ones((2,2)) #a 2x2 matrix of ones b = np.ones((2,3,4)) #a 2x3x4 matrix of ones. A 2x3 matrix with dim 4 arrays as entries print(b) c = np.eye(4) # an identity matrix with diagonal elements set to 1 and 0s everywhere else print(c) #[[1 0 0 0] # [0 1 0 0] # [0 0 1 0] # [0 0 0 1]] d = np.diag(np.array([2, 4, 6, 8])) #a diagonal matrix with diagonal entries as the elements of the inputed elements print(d) #[[2, 0, 0, 0], # [0, 4, 0, 0], # [0, 0, 6, 0], # [0, 0, 0, 8]] e = np.random.rand(4) #an array of length 4, with values as random floating points in the range [0,1] f = np.random.randn(4) #an array of lenghth 4 with gaussian random floating point numbers g = np.random.seed(1234) g = np.empty((2,2)) #a numpy array of shape 2x2 with random values as entries print(g) print(g.dtype) #data type of elemennts in array. should be "float64" #Complex data type a = np.array([1+2j, 3+4j, 5+6*1j]) print(a[2]) #5.+6.j a.dtype # "dtype('complex128')" #Indexing and Slicing a = np.arange(10) #array([0, 1, 2, 3, 4, 5, 6, 7, 8 , 9]) a[0] # 0 a[7] # 7 a[-1] # 9 a[-4] #6 a[::1] #array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) a[::-1] #reverses the array; whats really happening is the we're accessing elements starting from the back with a step count of 1 print(a[::2]) #array([0, 2, 4, 6, 8]) every other element print(a[2::2]) #start form the second element and access every other element print(a[-2::-2]) #a reversed array starting form the second to last, acessing every othe element in reverse print(a[:7]) #everything up until but not including the 7th index print(a[3:]) #everything following the 3rd index including the element at the 3rd index print(a[1:8:1]) #syntax (start, end, step size) start at the first number, and at the sencond (not inclusive), with a step size of the 3rd number a[:4] = 10 # assign all the values before index 4 (not inclusive) the number 10 print(a) a[4:] = 7 #assign all elements from index 4, including the element at index 4, the value of 7 print(a) print('\n') b = np.diag(a) #a diagonal matrix with diagonal entries as the elements of array a print(b) print('\n') print(b[:2]) #the rows before the 2nd row (not inclusive of the second row) print(b[::2]) #print every other row print(b[::3]) #print every fourth (row at index 3) row print(b[3::2]) #print every other row starting from the fourth (row at index 3 and every other row after) print('\n') print(b[::2, ::2]) #for every other row, access every other column print('\n') print(b[3:6,2:7]) #get the image of the matrix fromed by the 3-5th row, and 2nd-6th column print(b[(0,1,2,3,4,5,6,7,8,9), (0,1,2,3,4,5,6,7,8,9)]) # get the diagonals entries of the matrix
import argparse argument_pass = argparse.ArgumentParser() argument_pass.add_argument("-n", "--name", required=True, help="name of the user is required!") # -n is the shorthand for --name where either may be used in the cmd line # help string would give additional info in ther terminal when executed with the --help flag arguments = vars(argument_pass.parse_args()) # vars function turns the parsed cmd line args to python dictionary where the key to access the value is the name of the argument, # thus in this case is 'name' print(arguments) # -a boolean args option # -b string args option # -c integer args option # display a message using the arguments passed via cmd line input print("Hello {}, welcome to your virtual world, where all things are possible.".format(arguments["name"])) # args['key'] gives you the value associated with the given key in the dictionary # new directory
year = input('Введите год\n') if year.isdigit(): if int(year[-2:]) % 4 == 0: print('Год високосный') else: print('Год не високосный') else: print('Введите год ЦИФРАМИ')
import vectorlength import lineslope import degrees import vector import calculator import squareroot # if function. def t_if(): if choice == "calculator": calculator.cal() elif choice == "square root": squareroot.sqr() elif choice == "vector length": vectorlength.length_vector() elif choice == "line slope": lineslope.lineslope() elif choice == "degrees": degrees.deg() elif choice == "vector": vector.vector() else: print("Something went wrong. Make sure you spelled correctly.") while True: print("Enter what type of calculations you want.") print("You can choose 'Square root', 'Vector length', 'Calculator', 'Vector', 'Degrees' and 'Line slope'.") choice = input("Enter here: ").lower() if len(choice) > 0: t_if() else: print("Something went wrong. Make sure you spelled it correct.")
print("Enter n and m:") try: string_n, m = input().split() if string_n.isdigit() and m.isdigit(): sum, quantity = 0, int(m) if len(string_n) > quantity: for digit in list(string_n[:len(string_n) - int(quantity) - 1:-1]): sum += int(digit) print("The sum of the last {} digits of number {} is".format(quantity, string_n), sum) elif len(string_n) == quantity: for digit in string_n: sum += int(digit) print("The sum of the last {} digits of number {} is".format(quantity, string_n), sum) else: print("m must be less than number of digits n") else: print("You've entered not natural number") except ValueError: print("Please enter the second value")
students = [ { "name": "Mark", "age": 15 }, { "name": "Emily", "age": 14 }, { "name": "Joseph", "age": 15 } ] def add_student(name, age=15): new_student = { "name": name, "age": age } students.append(new_student) print(students) add_student("Liza") add_student("Acha", 43) add_student(name="Amma", age=40) print(students) def add_these_two_numbers(number1, number2): return number1 + number2 print(add_these_two_numbers(2, 5)) def my_print(value, *args): print(value) print(args) my_print("yo", "hey", "there", True, None, 15, "Thanks for reading this stuff!") ''' I'm commenting this out for convenience print("-------------------") user_name = input("Please enter *your* name here: ") print("The user's name is ", user_name) ''' print("-------------------") def nesting_function(): variable = "The example variable" def nested_function_1(): print("The example function") def nested_function_2(): # This is another example function print("Here I can use", variable) nested_function_1() nested_function_2() nesting_function()
#!/usr/bin/python """ Multiprocessing variant of sudoku1.py. Launches one process per option on the first '0' found. Lots of potential optimizations available from here. by Jason Price """ from __future__ import print_function import multiprocessing import random import sys # import time # 060900100308200000009006052400000005027080340500000008950700200000002607002004030 # 012345678901234567890123456789012345678901234567890123456789012345678901234567890 # 0 1 2 3 4 5 6 7 8 # s s s s s s s s s # bbb bbb bb* # rr*rrrrrr # c c c c c * c c c # 2 11 20 29 38 47 56 65 74 def same_row(i, j): """uses floor division. If floor division is equal for both, same row""" return (i // 9 == j // 9) def same_col(i, j): """if you're in the same column, subtracting indicies will result in a multiple of 9.""" return (i - j) % 9 == 0 def same_block(i, j): """divide i and j by 27... that will give which set of 3 rows it's in. i and j mod 9 divided by 3 will give which set of three rows it's in.""" return (i // 27 == j // 27 and i % 9 // 3 == j % 9 // 3) def r(a, lock, answer): # print('starting a is', a) if random.randint(0, 9) == 9 and answer.value != 0: return -1 i = a.find('0') if i == -1: answer.value = 1 print(a) return -1 excluded_numbers = set() for j in range(81): if same_row(i, j) or same_col(i, j) or same_block(i, j): excluded_numbers.add(a[j]) # with lock: # print(len(excluded_numbers), repr(excluded_numbers)) x = 0 for m in '123456789': if m not in excluded_numbers: x = r(a[:i] + m + a[i + 1:], lock, answer) if x == -1: # with lock: # print('got a neg1!') break if x == -1: return x # print("returning None. i is: " + str(i) + " j is: " + str(j) + " Excluded Numbers is: " + repr(sorted(list(excluded_numbers)))) # print(a) def r_mp(a): lock = multiprocessing.Lock() answer = multiprocessing.Value('i', 0) i = a.find('0') # if lock is None: # print("lock is None") if i == -1: print(a) return None excluded_numbers = set() for j in range(81): if same_row(i, j) or same_col(i, j) or same_block(i, j): excluded_numbers.add(a[j]) processes = [] for m in '123456789': if m not in excluded_numbers: # print('setting up process for m =', m) proc = multiprocessing.Process(target=r, args=(a[:i] + m + a[i + 1:], lock, answer)) processes.append(proc) for proc in processes: # print('starting a proc:') proc.start() # print('joining each proc:') for proc in processes: proc.join() # print('all joins done') # print("returning None. i is: " + str(i) + " j is: " + str(j) + " Excluded Numbers is: " + repr(sorted(list(excluded_numbers)))) # print(a) if __name__ == '__main__': if len(sys.argv) == 2 and len(sys.argv[1]) == 81: r_mp(sys.argv[1]) else: print('Usage: python sudoku.py puzzle') print(''' where puzzle is an 81 character string representing the puzzle read left-to-right, top-to-bottom, and 0 is a blank''')
#!/usr/bin/env python # this script will turn the Passive Buzzer on and then off import RPi.GPIO as GPIO import time # breadboard setup GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) # assign pin number for Passive Buzzer; pin 32 = GPIO 12 buzz_pin = 32 # set Passive Buaaer pin's mode as output GPIO.setup(buzz_pin, GPIO.OUT) # create Buzz function and set initial sound frequency to 1000 Hz Buzz = GPIO.PWM(buzz_pin, 1000) # change frequency and start Passive Buzzer using Buzz function with 50% duty for 1 second Buzz.ChangeFrequency(3000) Buzz.start(50) time.sleep(5) Buzz.stop() # reset GPIO resources used by script GPIO.cleanup()
import math def BSA(bWeight, bHeight): return math.exp( 0.425*math.log(float(bWeight)) +0.725*math.log(float(bHeight)) +math.log(71.84))/10000 def DailyDose(bWeight, bHeight, fDose): BSA_value=BSA(bWeight,bHeight) if (fDose in set(["y","Y"])): return 150*BSA_value else: return 200*BSA_value def CalcPillCount(bWeight,bHeight,fDose): daily_dose=DailyDose(bWeight,bHeight,fDose) dose_covered=0 count250=(daily_dose-dose_covered) // 250 dose_covered=dose_covered+250*count250 count100=(daily_dose-dose_covered) // 100 dose_covered=dose_covered+100*count100 count20=(daily_dose-dose_covered) // 20 dose_covered=dose_covered+20*count20 count5=(daily_dose-dose_covered) // 5 dose_covered=dose_covered+5*count5 return [count250,count100,count20,count5] def DoseCovered(pCounts): return pCounts[0]*250+pCounts[1]*100+pCounts[2]*20+pCounts[3]*5 def Main(): print("My name is _______________ and my student number is _____________") body_weight=input("Input body weight (kg): ") body_height=input("Input body height (cm): ") first_dose=input("Is this the first dose (Y/N): ") pill_count=CalcPillCount(body_weight,body_height,first_dose) daily_dose=DailyDose(body_weight, body_height,first_dose) dose_covered=DoseCovered(pill_count) print("") print("weight=", body_weight, "kg; height=", body_height, "cm\n\n") print("BSA=",BSA(body_weight,body_height)," sq. m") print("Daily Dose=",daily_dose,"mg/day") print("Dose Covered:", dose_covered, " mg/day") print("Pill counts:", pill_count[0], " of 250mg, ",pill_count[1], " of 100mg, ", pill_count[2]," of 20mg, ", pill_count[3], " of 5mg" ) print("error: ", dose_covered-daily_dose," mg/day") Main()
import os import csv num_votes = 0 results = {} with open('election_data.csv') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') next(csvreader, None) for row in csvreader: if not row[2] in results: results[row[2]] = 1 else: results[row[2]] += 1 print("Election Results\n-------------------------") print(f"Total Votes: {sum(results.values())}") print("-------------------------") results_sorted = [(val,key) for key,val in results.items()] for val,key in results_sorted: print(f"{key}: {val/sum(results.values()):.2%} ({val})") print("-------------------------") print(f"Winner: {results_sorted[0][1]}") print("-------------------------") with open('election_summary.txt', mode='w') as txtfile: text_to_write = ["Election Results\n", "-------------------------\n", f"Total Votes: {sum(results.values())}\n", "-------------------------\n"] txtfile.writelines(text_to_write) for val,key in results_sorted: txtfile.writelines(f"{key}: {val/sum(results.values()):.2%} ({val})\n") text_to_write = ["-------------------------\n", f"Winner: {results_sorted[0][1]}\n", "-------------------------"] txtfile.writelines(text_to_write)
nums = [0,1,2,2,3,0,4,2] val = 2 # count method returns the number of elements with the specified value while nums.count(val): # will loop through nums while val is in nums nums.remove(val) # removes val from nums while val is in nums (while loop, see above) print(nums)
def min_max_difference(numbers_array): min=numbers_array[0] max=numbers_array[0] difference=0 for num in numbers_array: if num<min: min=num if num>max: max=num difference = max-min return difference
# scoping x = 1 class A(): x = 3 class B: print x class C: x = 5 class B: def f(self): print x C.B().f() class D: x = 7 class E: class F: print x class G: def f(self): x = 9 class H: print x G().f() class I: x = 11 def f(self): print x I().f()
#!/bin/python name=["o2","yangqi"] name.append("++"); name.sort() for n in name: print n name[2]="fff" name.append('aa') for n in name: print n
print('Digite a expressão - Por exemplo 2 + 2 ou 2 * 2') result = str(input('Expressão: ')) print('Resultado: ', eval(result))
# -*- coding:utf-8 -*- # ジェネレータ # 処理の途中で値を返し、必要に応じて処理を再開できる def sample_generator(): print("call 1") yield "1st step" print("call 2") yield "2nd step" print("call 3") yield "3rd step" # ジェネレータオブジェクトを作成 gen_func = sample_generator() text = gen_func.__next__() # yieldまで実行 print(text) # 1st step text = gen_func.__next__() print(text) # 2nd step text = gen_func.__next__() print(text) # 3rd step print() # ループ処理でジェネレータ関数を実行 def sample_generator(): print("call 1") yield "1st step" print("call 2") yield "2nd step" print("call 3") yield "3rd step" gen_func = sample_generator() for text in gen_func: print(text) # フィボナッチ数列を返すジェネレータ def fibonacci_generator(): f0, f1 = 0, 1 while True: # この中が10回繰り返される yield f0 f0, f1 = f1, f0 + f1 gen_func = fibonacci_generator() for i in range(0, 10): # 10個取得する num = next(gen_func) print(num) print() # send()メソッド # 待機中のジェネレータに値を設定する def sample_generator(): text = yield "Good Morning" yield text yield text gen_func = sample_generator() text = next(gen_func) print(text) text = gen_func.send("Hello") print(text) text = next(gen_func) print(text) # thorw()メソッド # 待機中のジェネレータに例外を送信 # close()メソッド # 待機中のジェネレータを正常終了させる
# -*- coding: utf-8 -*- # map関数 # lambda式と組み合わせるとさらに簡略化が可能 from __future__ import print_function # 引数の値を2倍にする関数 def calc_double(val): return val * 2 x = 3 y = calc_double(x) print(x, y) data1 = [x for x in range(1, 100, 11)] # calc_doubleでdata1の全ての要素を2倍にする # data2はmapオブジェクトが格納されるため、appendなどできない data2 = map(calc_double, data1) print("{0}\n{1}\n".format(data1, data2)) # mapオブジェクトからリスト型へ変換する print("convert list") data2 = list(map(calc_double, data1)) print("{0}\n{1}\n".format(data1, data2)) # data2に要素をappend print("append") data2.append(1000) print(data2, "\n") # for文を使用する場合 print("for") data2 = list() for val in data1: data2.append(calc_double(val)) print(data2, "\n") # lambda式を使う print("lambda") data1 = [x for x in range(0, 5)] data2 = list(map(lambda x: x * 2, data1)) print("{0}\n{1}".format(data1, data2))
# -*- coding: utf-8 -*- # ファイル入出力 # open("ファイルパス", "モード") f = open("sample.txt", "r") # ファイルを開く text = f.read() # ファイル読み込み print(text) f.close() # ファイルを閉じる f = open("sample2.txt", "w") f.write("sample text 2") f.close() # ファイルの読み書き f = open("sample.txt", "r+") text = f.read() print(text) f.write("append\n") f.close() # with文 # close処理が自動的に呼び出される with open("sample.txt", "r+") as f: text = f.read() print(text) f.write("append2")
# -*- coding:utf-8 -*- # Pythonのif-elif-else # Pythonではスコープをインデント(タブ)で表す if(10 > 5): # 条件が真であれば実行 print("10は5より大きい") print() num1 = 8 if(num1 >= 10): print(str(num1) + "は10以上") else: print(str(num1) + "は10より小さい") print() # `else if`ではなく`elif`を使う # 論理和(||)は`or`演算子を使う # 論理積(&&)は`and`演算子を使う # 否定(!)は`not`演算子を使う score = 86 absences = 0 print("欠席日数は" + str(absences) + "です") if(absences < 6): print("あなたの評価点は" + str(score) + "です") if(score <= 100 and score >= 90): print("評価はS") elif(score < 90 and score >= 80): print("評価はA") elif(score < 80 and score >= 70): print("評価はB") elif(score < 70 and score >= 60): print("評価はC") else: print("評価はD") else: print("出席日数が足りないため単位不認定となりました")
def anumeric(st): word = st.split() l = [] for i in word: if not i.isalpha() and not i.isnumeric() and i.isalnum(): l.append(i) return l print(anumeric("prokash this2 value is5 alphanumaric and 123 &h12"))
import numpy as np import matplotlib.pyplot as plt from DeZero import Variable import DeZero.functions as F def main(): # dataset np.random.seed(0) x = np.random.rand(100, 1) y = np.sin(2 * np.pi * x) + np.random.rand(100, 1) # initialization of weights I, H, O = 1, 10, 1 W1 = Variable(0.01 * np.random.randn(I, H)) b1 = Variable(np.zeros(H)) W2 = Variable(0.01 * np.random.randn(H, O)) b2 = Variable(np.zeros(O)) # prediction of neural net def predict(x): y = F.linear(x, W1, b1) y = F.sigmoid_simple(y) # y = F.sigmoid(y) y = F.linear(y, W2, b2) return y lr = 0.2 iters = 10000 # learning for i in range(iters): y_pred = predict(x) loss = F.mean_squared_error(y, y_pred) W1.cleargrad() b1.cleargrad() W2.cleargrad() b2.cleargrad() loss.backward() W1.data -= lr * W1.grad.data b1.data -= lr * b1.grad.data W2.data -= lr * W2.grad.data b2.data -= lr * b2.grad.data if i % 1000 == 0: print(loss) t = np.linspace(0.0, 1.0, 100) plt.plot(x.T[0], y.T[0], 'bo', label="Target dots", linewidth=None) plt.plot(t, predict(t.reshape(100, 1)).T.data[0], 'r', label="Predicted curve") plt.xlabel("x") plt.ylabel("y") plt.legend() plt.show() if __name__ == "__main__": main()
# goal: receive a large peice of text via email from Bart and decrypt it here and send it back to him unencrypted import other_millers from math import gcd as bltin_gcd class RSA: def toBase10(self, n, alphabet): a = 0 for c in n: pos = alphabet.find(c) a *= len(alphabet) a += pos return a def fromBase10(self, n, alphabet): string = "" while n: pos = int(n % len(alphabet)) string += alphabet[pos] n //= len(alphabet) return(string[::-1]) def gcdExtended(self, a, b): # Base Case if a == 0: return b, 0, 1 gcd, x1, y1 = self.gcdExtended(b % a, a) # Update x and y using results of recursive # call x = y1 - (b//a) * x1 y = x1 return gcd, x, y def coprime2(self, a, b): return bltin_gcd(a, b) == 1 # Write a method called GenerateKeys that takes two very long text strings as input. def GenerateKeys(self, txt1, txt2): # Treat the text strings as base 26 numbers, and convert them to base 10 numbers alphabet = "abcdefghijklmnopqrstuvwxyz" txt1_base10 = self.toBase10(txt1, alphabet) txt2_base10 = self.toBase10(txt2, alphabet) # mod by 10^200 to make them the right size. Ensure that they were # longer than 10^200 before doing the mod, or print a Warning message. if txt1_base10 >= 10**200: right_size_1 = txt1_base10 % 10**200 else: print("number 1 not longer than 10^200") if txt2_base10 >= 10**200: right_size_2 = txt2_base10 % 10**200 else: print("number 2 not longer than 10^200") # Make them odd. Then start adding 2 until they are prime. if right_size_1 % 2 == 0: right_size_1 += 1 if right_size_2 % 2 == 0: right_size_2 += 1 # check against millers algorithm and add 2 until they become prime while other_millers.main([right_size_1]) == False: right_size_1 += 2 while other_millers.main([right_size_2]) == False: right_size_2 += 2 # Now you have your two, 200 digit prime numbers, p and q. # Calculate n = p*q n = right_size_1 * right_size_2 # Calculate r = (p-1)*(q-1) r = (right_size_1 - 1) * (right_size_2 - 1) # Find e – a 398 digit number that is relatively prime with r. q = 13810834549851754495631119119083264472163086356572107773582879923426598025862074679447336117815943749541796279436443039552933969374169788367012246195789046529533631022625525345800281418485860410760897 g = 1369130379653907728220329653863601998483759642997963321041916329355276363438824464509428450695834115276233573893780672690364403286484684834222612116667518454320778609664308572695691597523768521935011 e = q * g if e % 2 == 0: e += 1 while other_millers.main([e]) == False: e += 2 # n = int(input("Enter number:")) s = e count = 0 while(s > 0): count = count+1 s = s//10 # Find d – the inverse of e mod r. g, x, d = self.gcdExtended(r, e) # Save n and e to a file called public.txt (write them as text, with 1 return after each number) f = open("public.txt", "w") f.write(str(n)) f.write("\n") f.write(str(e)) f.close() # Save n and d to a file called private.txt fw = open("private.txt", "w") fw.write(str(n)) fw.write("\n") fw.write(str(d)) fw.close() # All other variables can be discarded. # Write a method called Encrypt that takes as parameters the name of an input text file and the name of an output text file. def Encrypt(self, inputfile, outputfile): # Open the input file (which should already exist in the current directory and # be full of plain text). Use binary mode, then convert the contents to text mode as follows: fin = open(inputfile, "rb") PlainTextBinary = fin.read() PlainText = PlainTextBinary.decode("utf-8") fin.close() alphabet = ".,?! \t\n\rabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" # Treat the input file text as a base 70 integer, and convert it to base 10, # using block sizes so as to not exceed integer n. public = open("public.txt") file_contents = public.read() contents = file_contents.splitlines() n = contents[0] e = contents[1] size_chunk = 216 chunks = [PlainText[i:i+size_chunk] for i in range(0, len(PlainText), size_chunk)] # Encode each block using the rules of RSA. (Read n and e from public.txt) fout = open(outputfile, "wb") i = 0 money = "$" for i in range(len(chunks)): chunks[i] = self.toBase10(chunks[i], alphabet) chunks[i] = pow(int(chunks[i]), int(e), int(n)) chunks[i] = self.fromBase10(chunks[i], alphabet) fout.write(chunks[i].encode("utf-8")) fout.write(money.encode("utf-8")) fout.close() # Write a method called Decrypt that takes as parameters the name of an input text file and the name of an output text file. def Decrypt(self, input, output): # Open the input file in binary mode (which should already exist and be full of encrypted text). # Use the same alphabet as above. fin = open(input, "rb") PlainTextBinary = fin.read() PlainText = PlainTextBinary.decode("utf-8") fin.close() alphabet = ".,?! \t\n\rabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" # Treat the input file text as a base 70 integer, and convert it to base 10, using block sizes as indicated by the $ signs. blocks = PlainText.split("$") # Decode each block using the rules of RSA. (Read n and d from private.txt) public = open("private.txt") file_contents = public.read() contents = file_contents.splitlines() n = contents[0] d = contents[1] fout = open(output, "wb") i = 0 for i in range(len(blocks)): blocks[i] = self.toBase10(blocks[i], alphabet) blocks[i] = pow(blocks[i], int(d), int(n)) blocks[i] = self.fromBase10(blocks[i], alphabet) fout.write(blocks[i].encode("utf-8")) fout.close() def main(): # Write a main function to test your codeour code # Make a class of type RSA # Generate the key files by calling GenerateKeys with two # very long strings of lowercase letters that only you would remember. # rsa.GenerateKeys("long text that only i remeber", # "long text that only i remember") rsa = RSA() rsa.GenerateKeys("viqopcxkqcomyyootqgqjoiiojtcamjfxflupncosozuiwseohhmhryzbxntwnkqxjbvntnzowoolihicjhnepqsmbkpahidrsyatybejuxfikrudqquahznvqmfxhcbuussqqasojwpskbgwsruzqzywbyehhrhxboplhxyzbrqokuqewcddy", "qwxaohhoolmdcngmrnzjefsmcskldwwlokdwlczldssmpwdpwfycojxdgkvenlzoksancwtjgtkihytjbpwpiahqjuvkppkbnawxtuzpiuiobdltfqkfhpyeqxdqhwtlwuazokucfvafkknsikvfhwygebgitkzgvtxlnbcwsymhfvzuftbiw") rsa.Encrypt("message.txt", "encrypted.txt") rsa.Decrypt("encrypted.txt", "decrypted.txt") # Make a plain text file consisting of only letters in the alphabet. # It should be long enough to require multiple encoding blocks. # Call your Encrypt method. # Call your Decrypt method. # Verify that the decoded output file exactly matches the original plain text file. main() # to pass off # Email me your public.txt (not private.txt) # I will use that to send you a message that only you can decrypt. # Email me back the decrypted message # All code should be of your own creation, except the Inverse Euclidean Algorithm, which you may get whatever help you can from the internet.
username = input("Input username: ") user_list= { "Quang Nguyen":{ "Name": "Nguyen Nhat Quang" , "Age":"21", "Gender":"Male", "Interest":"Football", }, "Thu Nguyen":{"Name": "Nguyen Thi Thu" , "Age":"37", "Gender":"Female", "Interest":"Play", }, "Quy Nguyen": { "Name": "Dinh Quy" , "Age":"20", "Gender":"Male", "Interest":"Laughing", }, "tuananhkid":{ "Name": "Nguyen Tuan Anh" , "Age":"19", "Gender":"Male", "Interest":"No interest", }, } display_list = [] error_message= "No data was found" if username in user_list: display_list.append(user_list[username]) else: display_list.append(error_message) print(display_list)
import os import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True # returns a compiled model # identical to the previous one model = tf.keras.models.load_model('image_classification_fine.h5') """As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 0.88 (or 88%) on the training data. ## Evaluate accuracy Next, compare how the model performs on the test dataset: """ image_size = 160 # All images will be resized to 160x160 batch_size = 32 train_path='train' # Rescale all images by 1./255 and apply image augmentation train_datagen = keras.preprocessing.image.ImageDataGenerator(rescale=1./255) # Flow training images in batches of 20 using train_datagen generator train_generator = train_datagen.flow_from_directory( train_path, # Source directory for the training images target_size=(image_size, image_size), batch_size=batch_size, class_mode='categorical') test_loss, test_acc = model.evaluate(train_generator) print('Test accuracy:', test_acc) """It turns out, the accuracy on the test dataset is a little less than the accuracy on the training dataset. This gap between training accuracy and test accuracy is an example of *overfitting*. Overfitting is when a machine learning model performs worse on new data than on their training data. ## Make predictions With the model trained, we can use it to make predictions about some images. """ predictions = model.predict(train_generator) def plot_image(i, predictions_array, classes, class_indices, img): predictions_array, true_label, img = predictions_array[i], true_label[i], img[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img, cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == true_label: color = 'blue' else: color = 'red' plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], 100*np.max(predictions_array), class_names[true_label]), color=color) """Let's plot several images with their predictions. Correct prediction labels are blue and incorrect prediction labels are red. The number gives the percent (out of 100) for the predicted label. Note that it can be wrong even when very confident.""" # Plot the first X test images, their predicted label, and the true label # Color correct predictions in blue, incorrect predictions in red num_rows = 5 num_cols = 3 num_images = num_rows*num_cols #plt.figure(figsize=(2*2*num_cols, 2*num_rows)) #for i in range(num_images): # plt.subplot(num_rows, 2*num_cols, 2*i+1) # plot_image(i, predictions, train_generator.classes, train_generator.class_indices, train_generator) # plt.subplot(num_rows, 2*num_cols, 2*i+2) # plot_value_array(i, predictions, test_labels) #plt.show() """Finally, use the trained model to make a prediction about a single image.""" # Grab an image from the test dataset img = test_images[0] print(img.shape) """`tf.keras` models are optimized to make predictions on a *batch*, or collection, of examples at once. So even though we're using a single image, we need to add it to a list:""" # Add the image to a batch where it's the only member. img = (np.expand_dims(img,0)) print(img.shape) """Now predict the image:""" predictions_single = model.predict(img) print(predictions_single) plot_value_array(0, predictions_single, test_labels) plt.xticks(range(10), class_names, rotation=45) plt.show() """`model.predict` returns a list of lists, one for each image in the batch of data. Grab the predictions for our (only) image in the batch:""" prediction_result = np.argmax(predictions_single[0]) print(prediction_result)
from math import * from numpy import * # from chapter05.paintUtils import * def loadDataSet(): dataMat = [] labelMat = [] fr = open("C:\\Users\\Mypc\\Desktop\\machinelearninginaction\\Ch05\\testSet.txt", ) arrayOLines = fr.readlines() for line in arrayOLines: lineArr = line.strip().split() dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])]) labelMat.append(int(lineArr[2])) # 这个是分类标签 return dataMat, labelMat # sigmoid函数 def sigmoid(inX): return 1.0 / (1 + exp(-inX)) #普通梯度上升 def gradAscent(dataMatIn, classLabels): dataMatrix = mat(dataMatIn) # 将传入的数据集列表转化为矩阵 labelMat = mat(classLabels).transpose() # 将传入的标签列表转化为其转置矩阵 ,即:[1*n] --> [n*1] m, n = shape(dataMatrix) # 获取矩阵的规格,这里是m行,n列 alpha = 0.001 # 初始化步长 maxCycles = 500 # 初始化迭代次数 weights = ones((n, 1)) # 初始化权重,即回归系数,这里是个向量n*1 for k in range(maxCycles): h = sigmoid(dataMatrix * weights) # 注意,这里是矩阵相乘!!![m*n] * [n*1] =[m*1] 为啥不把[1*1]放入其中??? error = (labelMat - h) #用于梯度上升 weights = weights + alpha * dataMatrix.transpose() * error # 迭代权重 ,transponse是求其转置矩阵 这里是 [n*m] * [m*1] = [n*1] return weights #随机梯度上升算法 def gradAscentBest(dataMatIn,classLabels,numIter =150): m,n = shape(dataMatIn) weights = ones(n) for j in range(numIter): dataIndex = list(range(m)) for i in range(m): alpha = 4/(1.0+i+j)+0.01 randIndex= int(random.uniform(0,len(dataIndex))) h = sigmoid(sum(dataMatIn[randIndex]*weights)) error = classLabels[randIndex] -h weights= weights + alpha * error * dataMatIn[randIndex] del(dataIndex[randIndex]) return weights def plotBestFit(weights): import matplotlib.pyplot as plt # weights=wei.getA() dataMat,labelMat=loadDataSet() dataArr=array(dataMat) n=shape(dataArr)[0] xcord1=[];ycord1=[] xcord2=[];ycord2=[] for i in range(n): if int(labelMat[i])==1: xcord1.append(dataArr[i,1]);ycord1.append(dataArr[i,2]) else: xcord2.append(dataArr[i,1]);ycord2.append(dataArr[i,2]) fig=plt.figure() ax=fig.add_subplot(111) ax.scatter(xcord1,ycord1,s=30,c='red',marker='s') ax.scatter(xcord2,ycord2,s=30,c='green') x=arange(-3.0,3.0,0.1) y=(-weights[0]-weights[1]*x)/weights[2]#最佳拟合直线 ax.plot(x,y) plt.xlabel('X1');plt.ylabel('X2') plt.show() # dataMat, labelMat = loadDataSet() # weights = gradAscentBest(array(dataMat), labelMat,150) # plotBestFit(weights) # print(ones((5,1)))
'''Obliczanie wartość bezwzględnej danej liczby jest najprostszym przykładem użycia algorytmu z decyzją. Dla danej liczby x wartość bezwzględna |x| wynosi: x jeżeli x ≥ 0, -x w przeciwnym wypadku. ''' from decimal import Decimal while True: print('wpisz liczbę:') x=int(Decimal(input())) if x>=0: wynik=x else: wynik=-x z=(('liczba: {0} = {1}').format(x,wynik)) print(z) ''' --------------------------------------------------- LUB --------------------------------------------------- ''' def main(): while True: print('wpisz liczbę:') x=int(Decimal(input())) if x>=0: wynik=x else: wynik=-x print((('liczba: {0} = {1}').format(x,wynik))) if __name__ == "__main__": main()
# generating sudoku grid filled with numbers def showgrid(): print("grid") for l in grid: print(l) def clear(num,x,y): print("clear") modx = int(x/3) mody = int(y/3) for a in range(len(grid)): moda = int(a/3) for b in range(len(grid[a])): if grid[a][b] == "": showgrid() print("eradsa") quit() modb = int(b/3) if not (x == a and y == b): sqr = ((modx == moda) and (mody == modb)) row = (x == a) cul = (y == b) if (sqr or row or cul) and type(grid[a][b]) == str: grid[a][b] = grid[a][b].replace(str(num),"") showgrid() print(nums) def generate(l): print("gen") if len(l) == 0: print("error on the way") showgrid() quit() return num = l[0] l.pop(0) print(l) count = 0 global grid bckp = grid skip = 0 while bckp == grid: skipped = 0 for x in range(len(grid)): for y in range(len(grid[x])): if type(grid[x][y]) == str: if str(num) in grid[x][y]: if skip == skipped: grid[x][y] = num count+=1 clear(num,x,y) elif skipped < skip: skipped +=1 grid[x][y] = grid[x][y].replace(str(num),"") if skipped > skip: print("waaat") if count != 9: print(f"{num} , {count}") print("ERRRRROR") skip+=1 if skip > (9-num): print("errrrrerrrrrrr") grid = bckp return l def done(): print("done") for x in range(len(grid)): for y in range(len(grid[x])): if type(grid[x][y]) != int: return False return True def main(): print("main") global nums nums = [i for i in range(1,10)] while not done(): nums = generate(nums) print(nums) showgrid() input() if __name__ == "__main__": grid = [["123456789" for i in range(9)] for i in range(9)] main()
# level 2 solving strategies # functions here: # from level2 import Naked_Multiple,Hidden_Multiple,Lines_2,NT,NT_chains,Y_Wing, def Naked_Multiple(unit): found = False for mult in range(3,8): done = [] for cell in range(len(unit)): if type(unit[cell]) == str: if len(unit[cell]) == mult and cell not in done: if unit.count(unit[cell]) == mult: indexes = [i for i in range(len(unit)) if unit[i] == unit[cell]] nums = [i for i in unit[cell]] done.extend(indexes) for c in range(len(unit)): if type(unit[c]) == str and c not in indexes: for num in nums: if num in unit[c]: found = True unit[c] = unit[c].replace(num,'') if found: return [unit,found] return [unit,found] def Hidden_Multiple(unit): found = False for mult in range(3,8): nums = [None] for num in range(1,10): nums.append([]) if num in unit: continue num = str(num) for ind in range(len(unit)): if type(unit[ind]) == str: if num in unit[ind]: nums[-1].append(ind) for num in range(1,len(nums)): if len(nums[num]) == mult: if nums.count(nums[num]) == mult: multiple = ''.join([str(v) for v in range(len(nums)) if nums[v] == nums[num]]) for ind in nums[num]: if unit[ind] != multiple: found = True unit[ind] = multiple if found: return [unit,found] return [unit,found] def Lines_2(grid): found = False for num in range(1,10): rows = [] cols = [] num = str(num) for x in range(9): r= [y for y in range(9) if (type(grid[x][y]) == str and num in grid[x][y])] c= [y for y in range(9) if (type(grid[y][x]) == str and num in grid[y][x])] rows.append(r) cols.append(c) rowind = [] for r in rows: if len(r) == 2 and rows.count(r) == 2: s = [i for i in range(len(rows)) if rows[i] == r] if s not in rowind: rowind.append(s) colind = [] for c in cols: if len(c) == 2 and cols.count(c) == 2: s = [i for i in range(len(cols)) if cols[i] == c] if s not in colind: colind.append(s) if colind or rowind: for pair in rowind: keep = [] c = [] for x in pair: for y in rows[x]: if [x,y] not in keep: keep.append([x,y]) c.append(y) for y in c: for x in range(9): if [x,y] not in keep: if type(grid[x][y]) == str: if num in grid[x][y]: found = True grid[x][y] = grid[x][y].replace(num,'') for pair in colind: keep = [] r = [] for y in pair: for x in rows[x]: if [x,y] not in keep: keep.append([x,y]) r.append(y) for x in c: for y in range(9): if [x,y] not in keep: if type(grid[x][y]) == str: if num in grid[x][y]: found = True grid[x][y] = grid[x][y].replace(num,'') return [grid,found] def NT(grid): nt = [] for x in range(9): for y in range(9): if type(grid[x][y]) == str: if len(grid[x][y]) == 2: nt.append([grid[x][y],x,y,str(int(x/3))+str(int(y/3))]) return nt #[ [value,x,y,sqr] , ... ] def NT_chains(nakedtwos = []): chains = [] for c in range(len(nakedtwos)): usedchain = [c] cell = nakedtwos[c] available = [] for c2 in range(len(nakedtwos)): if c2 not in usedchain: ncell = nakedtwos[c2] com1 = (cell[0][0] in ncell[0]) com2 = (cell[0][1] in ncell[0]) com = ((com1 or com2))# and com1 != com2 ) inrow = (cell[1] == ncell[1]) incol = (cell[2] == ncell[2]) insqr = (cell[3] == ncell[3]) relevant = ((inrow or incol or insqr) and com) if relevant: usedchain.append(c2) available.append([c2,com1,com2,inrow,incol,insqr]) chains.append(available) return chains # [[[1, False, True, False, False, True]], [[0, True, False, False, False, True]], def Y_Wing(grid): found = False nakedtwos = NT(grid) # print(nakedtwos) if not nakedtwos: return [grid,found] chains = NT_chains(nakedtwos) # print(chains) for c in range(len(chains)): cc = chains[c] if len(cc) > 1: for cell in cc: for cell2 in cc: if cell != cell2: difval = ( cell[1] == cell2[2] ) rowcol = ( ( cell[3] and cell2[4] ) or ( cell[4] and cell2[3] ) ) rowsqr = ( ( cell[3] and cell2[5] ) or ( cell[5] and cell2[3] ) ) colsqr = ( ( cell[4] and cell2[5] ) or ( cell[5] and cell2[4] ) ) if difval and (rowcol or rowsqr or colsqr): # almost bingo indexes = [c,cell[0],cell2[0]] # print(indexes) # last check needed vals = [] for index in indexes: for v in nakedtwos[index][0]: vals.append(v) vals = set(vals) if len(vals) == 3: # bingo ! cant = [v for v in vals if v not in nakedtwos[c][0]] # print(f'nak {c} = {nakedtwos[c][0]}') # print(f'cant = {cant}') cant = cant[0] # print(f' ntc = {nakedtwos[c]}') # print(f'cant = {cant}') if rowcol: if cell[3] and cell2[4]: # cell in row, == c[x] == cell[x] # cell2 in col == c[y] == cell2[y] xx = 1 yy = 2 else: xx = 2 yy = 1 newy = nakedtwos[indexes[xx]][yy] newx = nakedtwos[indexes[yy]][xx] if type(grid[newx][newy]) == str: if cant in grid[newx][newy]: found = True grid[newx][newy] = grid[newx][newy].replace(cant,'') else: # sqr included checkxy = [] # print(cell,cell2) # print(indexes) if cell[-1]: # sqr sq = indexes[1] ot = indexes[2] ot2 = cell2 # print(sq,ot,ot2) else: sq = indexes[2] ot = indexes[1] ot2 = cell if ot2[3]:# row xx = nakedtwos[ot][1] yy = nakedtwos[sq][2] checkxy.append([xx,yy]) xx = nakedtwos[sq][1] # modx = int(nakedtwos[sq])[3][0] mody = int(nakedtwos[ot][3][1]) for y in range(mody*3,(mody+1)*3): checkxy.append([xx,y]) else: # sqr col yy = nakedtwos[ot][2] xx = nakedtwos[sq][1] checkxy.append([xx,yy]) yy = nakedtwos[sq][2] modx = int(nakedtwos[ot])[3][0] for x in range(modx*3,(modx+1)*3): checkxy.append([xx,yy]) # print(checkxy) for coord in checkxy: x = coord[0] y = coord[1] if type(grid[x][y]) == str: if cant in grid[x][y]: found = True grid[x][y] = grid[x][y].replace(cant,'') return [grid,found]
import random class die: """Class for die objects. attributes: sides (int) : Number of sides the dice has (default is 6) methods: change_sides(new_side) : changes the number of sides roll_die() : returns a random integer from 1 to number of sides """ sides = 6 # comment def change_sides(self, new_side): self.sides = new_side def roll_die(self): return random.randint(1, self.sides) dice1 = die() print(dice1.sides) print(dice1.roll_die()) dice1.change_sides(10) print(dice1.sides) print(dice1.roll_die())
import random def addition(n): somme = 0 for i in range(1, n+1): somme = somme + i print(somme) #addition(3) #addition(8) ######################################################## def fibo(): n2 = 0 n1 = 1 suite = [0] for i in range(1, 20): somme = n1 + n2 n2 = n1 n1 = somme suite.append(somme) print(suite) #fibo() ######################################################## def testTableau(t, n): if(n in t): print("L'entier " + str(n) + " se trouve dans le tableau") else: print("L'entier " + str(n) + " ne se trouve pas dans le tableau") tableau = [3, 5, 0, 4] #testTableau(tableau, 5) #testTableau(tableau, 6) ######################################################### def inArray(table, var): for i in table: if(i == var): print("L'entier " + str(var) + " se trouve dans le tableau") return print("L'entier " + str(var) + " ne se trouve pas dans le tableau") #inArray(tableau, 5) #inArray(tableau, 6) ########################################################## def indexTab(tab, var): l = len(tab) for i in range(0, l): if(var == tab[i]): print("L'entier " + str(var) + " se trouve dans le tableau a la position " + str(i)) T = [3,5,0,4,4,7] #indexTab(T, 4) ########################################################### def returnIndex(array, var): k = 0 indice = list() for i in array: if i == var: indice.append(k) k = k + 1 print("L'entier se trouve a la position " + str(indice)) #returnIndex(T, 4) ####################################################### def palindromme(text): l = len(text) indexFin = l-1 for i in range(0, l): if(text[i] != text[indexFin]): print("Le mot " + text + " n'est pas un palindromme") return indexFin = indexFin - 1 print("Le mot " + text + " est un palindromme") #texte = raw_input("Test du mot : ") #palindromme(texte) ##################################################### def nbPrem(n): for i in range(2,n-1): if n % i == 0: # print(str(n) + " divisible par " + str(i)) return False return True def listNb(): for n in range(2,99): if nbPrem(n) == True: print("Nombre premier " + str(n)) #listNb() ################################################# def comparateur(): max = 0; for i in range(0,10): chiffre = raw_input("Entrez un chiffre : ") if(int(chiffre) > max): max = int(chiffre) print("Le plus grand chiffre que vous avez entre est " + str(max)) #comparateur() ################################################ def montyHall(): nbSimul = 1000 sommeTestChange = 0 sommeTestChangeGagne = 0 sommeTestGarde = 0 sommeTestGardeGagne = 0 pourcentChange = 0 pourcentGarde = 0 for i in range(0, nbSimul): #portes, pactol et choix1 cree portes = [1, 2, 3] gagne = random.choice(portes) choix1 = random.choice(portes) #porte sans cadeau : on remove le pactol (gagne) porteRestanteVide = [1, 2, 3] porteRestanteVide.remove(gagne) #si le joueur a choisi la porte gagnante, on supprime le choix1 des portes vides if(gagne != choix1): porteRestanteVide.remove(choix1) #on choisit parmi les portes vides la porte a ouvrir et on l'enleve des portes porteOuverte = random.choice(porteRestanteVide) portes.remove(porteOuverte) #parmi les portes restantes, on fait un choix2 choix2 = random.choice(portes) #si le choix2 = choix1, on calcule le pourcentage de gain if(choix2 == choix1): sommeTestGarde = sommeTestGarde + 1 if(choix2 == gagne): sommeTestGardeGagne = sommeTestGardeGagne + 1 pourcentGarde = sommeTestGardeGagne * 100 / sommeTestGarde # si le choix2 != choix1, on calcule le pourcentage de gain if (choix2 != choix1): sommeTestChange = sommeTestChange + 1 if (choix2 == gagne): sommeTestChangeGagne = sommeTestChangeGagne + 1 pourcentChange = sommeTestChangeGagne * 100 / sommeTestChange if(nbSimul < 10): print("Le pactol se trouve ici : " + str(gagne)) print("Le choix 1 est : " + str(choix1)) print("Les portes restantes sont : " + str(porteRestanteVide)) print("La porte ouverte est : " + str(porteOuverte)) print("Le taux de reussite en changeant de porte est de " + str(pourcentChange) + "%") print("Le taux de reussite en gardant la porte est de " + str(pourcentGarde) + "%") #montyHall()
#classes is collection of methods and variables#Multiple object #Inheritance..existing the existing method for child class #Operator overloading.. class Account1: #class variable (b_name) and instance variable (uname) - we use it with an instance; class function and instance function #instance object and class object#class object will be created when class is created b_name='ICICI' #class variable #static def adduser(self, u): #adduser(a, u1) once you call as a.adduser(u1) self.uname=u def viewuser(self): return self.uname def __init__(self): #init is constructor print('Account logic here') def viewrules(): #no self hence you can directly call with classname.method name..if self..then you have create object and then call return 'Some Rules' a=Account1()#calls init at this point b=Account1()#calls init at this point a.adduser('u1') b.adduser('u2') print(a.viewuser()) print(b.viewuser()) print(Account1.b_name) print(Account1.viewrules()) class Account2(Account1): #b_name='HDFC' def addaadhar(self, a): self.aadhar=a def viewaadhar(self): return self.aadhar def __init__(self): print('CA logic') super().__init__()#to call parent class init #Account1.__init__(self) another way of calling c=Account2() c.adduser('U3') c.addaadhar('A1') print(c.viewuser()) print(Account1.b_name) Account1.viewrules() print(c.viewaadhar()) class RBI: def RBIrules(self): return 'RBI rules' class Account3(Account2, RBI):#multiple inheritance ..search will happen from left to right classes def message(self): return 'Inside Account3' d=Account3() d.adduser('U4') d.addaadhar('A4') print(d.viewuser()) print(d.viewaadhar()) print(Account3.b_name) print(Account3.viewrules()) print(d.RBIrules()) class govt: def RBIrules(self): return 'govt rules' class Account4(Account2, RBI): def __init__(self): self.grules=govt() e=Account4() e.adduser('U5') e.addaadhar('A5') print(e.viewuser()) print(e.viewaadhar()) print(Account3.b_name) print(Account3.viewrules()) print(e.RBIrules()) print(e.grules.RBIrules()) class Account5: def __init__(self, n): self.name=n def __add__(self, other): return 'Hello ' + self.name + ' and ' + other.name X=Account5('abc') Y=Account5('XYZ') Z=X+Y print('Z= ', Z)
class Normal: def __init__(self, x=0, y=0, z=0): try: (self.x, self.y, self.z) = x except TypeError: self.x = x self.y = y self.z = z def __mul__(self, norm): return (self.x * norm.x) + (self.y * norm.y) + (self.z * norm.z) def __repr__(self): return f"Normal(x={self.x}, y={self.y}, z={self.z})"