text
stringlengths
37
1.41M
from Node import Node # Creat a Doubly Linked List (Traversing / Insertion / Deletion / searching) class DoublyLinkedList: # create a new class DoublyLinkedList def __init__(self): # then create a constructor self.head = Node() # creat a head and put on node self.head = None # define head as none self.len = 0 # define DoublyLinkedList length as 0 # method to foreword printing def print_LL(self): if self.head is None: # check head is none or not print("linked list is empty") # if head = none, print a massage else: # then create a variable as n and assign head to it n = self.head while n is not None: # while n is not none print the value of n and get next value of the DoublyLinkedList in to n print(n.data, ">>", end=' ') n = n.nref # when n is none loop will stop # method to backward printing def print_LL_reverse(self): print() if self.head is None: # check head is none or not print("Linked list is empty") # if head = none, print a massage else: n = self.head # create a variable and assign head to it. while n.nref is not None: # get the next value of the n and run loop until next value of the n is not none to get next of the n n = n.nref while n is not None: # while n is not none print the value n and get the previous value of the n in to variable n print(n.data, ">>", end=' ') n = n.pref # insert empty linked list def insert_empty(self, data): # we create insert empty link list and take parameter self and data if self.head is None: # firstly we check list empty or not new_node = Node(data) # if it is none then create new node and we create a node using node class and pass the data self.head = new_node # after creating node we point to new node self.len += 1 # increase length by 1 else: print("lined list is not empty") # link list is not empty, print a massage # add the beginning linked list def add_begin(self, data): new_node = Node() # create a new node pass the data parameter new_node.setData(data) # pass the data if self.head is None: # we check head is none self.head = new_node # after creating a node we need to point to new node else: new_node.nref = self.head # define the next of the created new node is to current head self.head.pref = new_node # previous of the current head is new node self.head = new_node # current head is new node self.len += 1 # increase length by 1 # add the end linked list def add_end(self, data): new_node = Node() # create a new node pass the data parameter new_node.setData(data) # pass the data if self.head is None: # we check head is none self.head = new_node # after creating a node we need to point to new node else: n = self.head # create a variable and assign head to it. while n.nref is not None: # get the next value of the n and run loop until next value of the n is not none to get next of the n n = n.nref n.setNext(new_node) # then n is none set the next of the end is new node new_node.setPrevious(n) # set n as the previous of ne node self.len += 1 # increase length by 1 # remove the begging linked list def remove_begin(self): # create a method to remove the head if self.head is None: # check head is none or not return None # if head = none return none else: next = self.head.nref # create a variable as next and next value of the head assign to it. self.head = next # define the head next.setPrevious(None) # previous of the head set as none self.len -= 1 # decrease length by 1 # remove the end linked list def remove_end(self): # create a method to remove the end if self.head is None: # check head is none or not return None # if head = none return none else: n = self.head # create a variable and assign head to it. while n.nref is not None: # get the next value of the n and run loop until next value of the n is not none to get next of the n n = n.nref n = n.pref # get the previous value of end n.setNext(None) # set the next of the end as none self.len -= 1 # decrease length by 1 # add the positional node def add_nodePosition(self, pos, data): # create a method and pass the position and data if pos < 0 or pos > self.len - 1: # set the given position is less than 0 or grater than length - 1 return None # then if it is return none elif pos == 0: # checked the position == 0 self.add_begin(data) # call the method add_begin(data) elif pos == self.len - 1: # checked given position self len -1 self.add_end(data) # then call the method add_end(data) else: new = Node() # create a new node and set the data new.setData(data) count = 0 # create a variable and set it value as 0 n = self.head # create a variable and assign head in to it while count != pos - 1: # run loop until count != position n = n.nref # get the next of the n in to n count += 1 # increase length by 1 x = n.nref # get the next of the end in to variable x n.setNext(new) # set the new node as the next of the n new.pref = n # set the n as the previous of the new new.nref = x # set the x as the next of the new x.pref = new # set the new as the previous of x self.len += 1 # increase length by 1 # remove the positional node def remove_nodePosition(self, pos): # create a method and pass the position if pos < 0 or pos > self.len - 1: # checked the given position is less than or 0 or grater than length - 1 return None # if it is return none elif pos == 0: # if pos == 0 , then call the method remove_begin() self.remove_begin() elif pos == self.len - 1: # if position = length - 1 ,then call the method remove remove_end() self.remove_end() else: count = 0 # create a variable and set it value as 0 n = self.head # create a variable and assign head in to it while count != pos: # run loop until count != position n = n.nref # get the next of the n in to n count += 1 # increase length by 1 x = n.pref # create variable x and set the value of x is previous of the n y = n.nref # create a variable y and set the value of the y is next of the end x.setNext(y) # set the next of the x is y y.setPrevious(x) # set the previous of the y is x self.len -= 1 # decrease length by 1 # create search_given def search_given(self, pos): # create a method and pass the position if pos < 0 or pos > self.len - 1: # checked the given position is less than or 0 or grater than length - 1 return None # if it is return none elif pos == 0: return self.head.data elif pos == self.len - 1: # if position = length - 1 ,then assign head to variable n n = self.head while n.nref is not None: # run loop until next of the n is not non , get next of n in to variable n n = n.nref return n.data # when next of the n is none return data of the n else: count = 0 # create a variable and set it value as 0 n = self.head # create a variable and assign head in to it while count != pos: # run loop until count != position n = n.nref # get the next of the n in to n count += 1 # increase count by 1 return n.data # return the data of the n # create a new function for the doubly length def Doubly_Length(self): n = self.head # create a variable n and assign the head count = 0 # create a variable and set it value as 0 while n is not None: # run loop until n is not none count += 1 # increase count by 1 n = n.nref # get the next of the n in to n return count # return the count
# Given a list of strings words representing an English Dictionary, find the # longest word in words that can be built one character at a time by other words # in words. If there is more than one possible answer, return the longest word with # the smallest lexicographical order. def longestword(words): print('testing') #wordset = set(words) words.sort() ans='' for w in words: if len(w) > len(ans) : if all(w[:i] in words for i in range(1,len(w))): ans=w print('Result is:',ans) # using Trie data structure # main starts here if __name__=='__main__': print('main started') words=['w','wo','wor','worl','world','aa'] #words = ["a", "bbb", "banana", "app", "appl", "ap", "apply", "apple"] longestword(words)
str='303' temp_output=[] # adding single digit characters for i in range(len(str)): temp_output.append(str[i]) print(temp_output) # adding combination of two pairs for i in range(len(str)): for j in range(i+1,len(str)): temp_output.append(str[i]+str[j]) print(temp_output) count=0 for char in temp_output: if (len(char) > 1 and char[0]!='0') or len(char) == 1: print(f'char {char}') if int(char)%3 == 0: count=count+1 print(count)
# minimum number of coins needed to make target t #DP using memorization technique to prevent the sample sub problem being solve again and agin # Formula # f(i,t) = min( f(i,t-val)+1 , f[i-1,t]) # final answer f(n-1,t) # import math def changeMake(arr,target): cache={} def subproblem(i,t): print(cache) # check if this sub problem input is already solved - Memorization if (i,t) in cache: return cache[(i,t)] # compute the lowest number of coins we need if choosing to take a coin of the current denomination val= arr[i] # case 1 : Considering the val # current denomination is too large if val > t: choice_take = math.inf #math infinity elif val==t: #target reached choice_take=1 else: #take and recurse choice_take= 1 + subproblem(i,t-val) # case 2 : compute the lowest number of coins we need if not taking any more coins of the current denomination if i==0: #not an option if no more denominations choice_leave = math.inf print(choice_leave) else: # recurse with remaining denominations choice_leave=subproblem(i-1,t) #in recursive these are the last steps #print(f'choice_take:{choice_take},choice_leave :{choice_leave}') optimum = min(choice_take,choice_leave) cache[(i,t)]=optimum return optimum return subproblem(len(arr)-1,target) if __name__== '__main__': arr= [8,3,1,2] target=3 print('main called:', changeMake(arr,target))
# formual total zeros count > (row * col)//2 def sparsematrix(a): zero_count=0 for i in range(len(a)): for j in range(len(a)): if a[i][j] == 0: zero_count+=1 if zero_count > (len(a)*len(a[0]))//2: return True else: return False array = [ [ 1, 1, 0 ], [ 0, 0, 4 ], [ 6, 0, 0 ] ] if (sparsematrix(array)) : print("Yes") else : print("No")
#Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. #Example 1: Input: n = 3 #Output: ["((()))","(()())","(())()","()(())","()()()"] def genParentheses(n): output=[] def backtrack(s,left,right): if len(s) == 2 * n: output.append(''.join(s)) return if left < n: s.append('(') backtrack(s,left+1,right) s.pop() if right < left: s.append(')') backtrack(s, left , right+1) s.pop() backtrack([],0,0) return output for i in range(1,5): print(genParentheses(i))
a=[[0,4],[1,3]] b=[[3,2],[5,1]] #a+b = [[3,6],[6,4]] for i in range(len(a)): for j in range(len(b)): print((a[i][j] + b[i][j]), end=' ') print('')
class TreeNode: def __init__(self,data): self.data=data self.children=[] self.parent=None def add_child(self, child): child.parent=self self.children.append(child) def print_tree(self): spaces = ' ' * self.get_level() * 3 prefix = spaces + '|__' if self.parent else '' print(prefix + self.data) for child in self.children : child.print_tree() def get_level(self): ancestor=0 p= self.parent while p: p=p.parent ancestor+=1 return ancestor def build_tree(): root = TreeNode('Electronics') laptop = TreeNode('Laptop') laptop.add_child(TreeNode('Dell')) laptop.add_child(TreeNode('Lenovo')) Cellphone = TreeNode('Cell Phone') Cellphone.add_child(TreeNode('Apple')) Cellphone.add_child(TreeNode('Samsung')) tv=TreeNode('TV') tv.add_child(TreeNode('LG')) tv.add_child(TreeNode('Sony')) root.add_child(laptop) root.add_child(Cellphone) root.add_child(tv) return root if __name__ == '__main__' : root = build_tree() root.print_tree() print("Root level is :", root.get_level())
"""Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order. A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. Example 1: Input: matrix = [[3,7,8],[9,11,13],[15,16,17]] Output: [15]""" class LuckyNoMatrix: def luckyNumbers(self,mat): min_row = [min(row) for row in mat] max_row=[] for row in zip(*mat): max_row.append(max(row)) #return list(set(min_row) & set(max_row)) return [i for i in min_row if i in max_row] if __name__ == '__main__' : print('Main has started :') martices = [ [[3, 7, 8], [9, 11, 13], [15, 16, 17]], [[1,10,4,2],[9,3,8,7],[15,16,17,12]], [[7,8],[1,2]] ] obj = LuckyNoMatrix() for mat in martices: print(mat, ':', obj.luckyNumbers(mat))
def rob(nums): r1, r2 = 0, 0 for amount in nums: temp= max(amount+r1, r2) r1, r2 = r2,temp print('Max amount of rob:', r2) # formula max(val + f(n-2) or f(n-1)) def MaxFlowerPlant(arr): a=0 #f(n-2) b=0 #f(n-1) for val in arr: temp=max(val+a,b) a,b= b,temp print('max sum of non-consecutive elements:',b) if __name__ =='__main__': a=[3,10,3,1,2,5] MaxFlowerPlant(a) rob(a)
# Binary Search Iteration def BinsearchIterative(a, val): lower = 0 upper = len(a) - 1 while lower <= upper : mid = (lower + upper) // 2 if val == a[mid]: return mid elif val < a[mid]: upper = mid - 1 else: lower = mid + 1 return -1 # Binary search Recursion def BinsearchRecurrsion(a, lower, upper, val): #base condition if lower > upper : return -1 mid = (lower + upper) // 2 if val == a[mid]: return mid elif val < a[mid]: return BinsearchRecurrsion(a,lower,mid - 1,val) else: return BinsearchRecurrsion(a, mid + 1, upper, val) if __name__=='__main__': a=[1,2,3,4,5,10] print('Org array: ',a) print('Binary search using Iteration o/p') for val in a: print(f'value: {val} at index :', BinsearchIterative(a,val)) print('Org array: ', a) print('Binary search using recursion o/p') lower=0 upper=len(a)-1 for val in a: print(f'value: {val} at index :', BinsearchRecurrsion(a,lower,upper,val))
def SIN(A,B): return A/B def COS(A,B): return A/B def TAN(A,B): return A/B print("ATURAN TRYGONOMETRI") while True : print("Menu pilihan:\n") print("1. SIN\n") print("2. COS\n") print("3. TAN\n") pilih=int(input("Masukkan pilihan :")) if pilih==1: A=int(input("Masukkan Depan:")) B=int(input("Masukkan Miring:")) print("hasil dari SIN adalah {}".format(SIN(A,B))) elif pilih==2: A=int(input("Masukkan Samping:")) B=int(input("Masukkan Miring:")) print("hasil dari COS adalah {}".format(COS(A,B))) elif pilih==3: A=int(input("Masukkan Depan:")) B=int(input("Masukkan Samping:")) print("hasil dari TAN adalah {}".format(TAN(A,B))) else : print("pilihan tidak ada")
import random import string from account import Account class Credentials: """ Class that generates new instances of credentials """ list_of_credentials = [] def __init__(self,social_media,user_name,password): """ __init__ method that helps us define properties for our objects. """ self.social_media = social_media self.user_name = user_name self.password = password def save_this_credentials(self): """ save_this_credentials saves credentials """ Credentials.list_of_credentials.append(self) def delete_credentials(self): """ delete_credentials method that deletes credentials """ Credentials.list_of_credentials.remove(self) @classmethod def find_credentials(cls,name_of_social_media): """ find_credentials method that searches for credentials """ for credentials in cls.list_of_credentials: if credentials.social_media == name_of_social_media: return credentials @classmethod def password_generate(cls): """ Generate a random password using string of letters and digits and special characters """ size = 8 charact = string.ascii_letters + string.digits + string.punctuation pass_word = ''.join(random.choice(charact)for i in range(size)) return pass_word @classmethod def display_credentials(cls): """ This will display all credentials we have in our credential list """ return cls.list_of_credentials @classmethod def credentials_exist(cls,name_of_social_media): ''' Method that checks if a contact exists from the contact list. Args: number: Phone number to search if it exists Returns : Boolean: True or false depending if the contact exists ''' for credentials in cls.list_of_credentials: if credentials.social_media == name_of_social_media: return True return False
#Merge sort an array def sort(arr): if len(arr) == 1: return arr mid = len(arr)//2 X = sort(arr[:mid]) Y = sort(arr[mid:]) i = j = 0 for k in range(len(arr)): if i != len(X) and (j == len(Y) or X[i] < Y[j]): arr[k] = X[i] i += 1 else: arr[k] = Y[j] j += 1 return arr arr = [1, 3, 5, 2, 4, 6] print(sort(arr))
class Animal(object): def __init__(self, name, health): self.name = name self.health = health def walk(self): self.health -= 1 return self def run(self): self.health -= 5 return self def displayHealth(self): print "Health: {}".format(self.health) return self class Dog(Animal): def __init__(self): super(Dog, self).__init__("dog", 150) def pet(self): self.health += 5 return self class Dragon(Animal): def __init__(self): super(Dragon, self).__init__("dragon", 170) def fly(self): self.health -= 10 return self def displayHealth(self): super(Dragon, self).displayHealth() print "I am a Dragon" return self animal1 = Animal("Generic Animal", 100).walk().walk().walk().run().run().displayHealth() dog1 = Dog().walk().walk().walk().run().run().pet().displayHealth() #.fly() Doesn't work! dragon1 = Dragon().fly().displayHealth()
class Bin_Heap: ''' chidren at indeces 2 * i and 2 * i + 1 their parents at indeces floor(i / 2) heap_list[0] - wasted element ''' def __init__(self): self.heap_size = 0 self.heap_list = [0] def perc_up(self, k): while k // 2 > 0: if self.heap_list[k] < self.heap_list[k // 2]: self.heap_list[k], self.heap_list[k // 2] =\ self.heap_list[k // 2], self.heap_list[k] else: break k //= 2 def perc_down(self, k): while k * 2 <= self.heap_size: tmp = self.min_child(k) if self.heap_list[k] > self.heap_list[tmp]: self.heap_list[k], self.heap_list[tmp] =\ self.heap_list[tmp], self.heap_list[k] else: break k = tmp def min_child(self, k): if 2 * k + 1 > self.heap_size: return 2 * k elif self.heap_list[2 * k] < self.heap_list[2 * k + 1]: return 2 * k else: return 2 * k + 1 def insert(self, k): self.heap_list.append(k) self.heap_size += 1 self.perc_up(self.heap_size) def extract_min(self): ''' weird logic, but it works ''' extracted = self.heap_list[1] self.heap_list[1] = self.heap_list[self.heap_size] self.heap_list.pop() self.heap_size -= 1 self.perc_down(1) return extracted def heap_construct(self, array): self.heap_size += len(array) self.heap_list = self.heap_list + array[:] k = len(array) // 2 while k > 0: self.perc_down(k) k -= 1 def main(): array = [24, 2, 9, 7, 4] test = Bin_Heap() test.heap_construct(array) test.insert(int(input())) print(test.extract_min()) print(test.extract_min()) print(test.extract_min()) print(test.extract_min()) print(test.extract_min()) print(test.extract_min()) if __name__ == '__main__': main()
def findEmpty(board): for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 0: return (i, j) return None def valid(board, num, pos): row = pos[0] column = pos[1] #checking rows for i in range(len(board[0])): if board[row][i] == num and column != i: return False #checking columns for i in range(len(board)): if board[i][column] == num and row != i: return False #checking box startRowBox = row//3 startColumnBox= column//3 for i in range(startRowBox*3, (startRowBox*3)+3): for j in range(startColumnBox*3, (startColumnBox*3)+3): if board[i][j] == num and row != i and column != j: return False return True def solve(board): find = findEmpty(board) if not find: return True else: row, col = find for i in range(1,10): if valid(board, i, find): board[row][col] = i if solve(board): return True board[row][col] = 0 return False
import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn import datasets, linear_model#DATASETS HAVE EXAMPLE DATASETS ,LINEAR_MODEL CONTAINS THE ALGORITHM from sklearn.metrics import mean_squared_error, r2_score #SKLEARN.METRICS=CONFUSION MATRIX,MEAN AND R2 USED FOR TALLYING AFTER TRAINING THE MODEL diabetes = datasets.load_diabetes() diabetes_X = diabetes.data[:,np.newaxis,2]#DATA FROM ALL THE ROWS THEN CONVERTING TO COLUMN print(diabetes_X) # Split the data into training/testing sets diabetes_X_train = diabetes_X[:-30] diabetes_y_train = diabetes.target[:-30] # Split the targets into training/testing sets diabetes_X_test = diabetes_X[-30:] diabetes_y_test = diabetes.target[-30:] #len(diabetes_X_test) # Plot outputs plt.scatter(diabetes_X_test, diabetes_y_test, color='blue') #plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3); plt.xticks(()) #A list of positions at which ticks should be placed. You can pass an empty list to disable xticks. plt.yticks(()) plt.show() regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(diabetes_X_train, diabetes_y_train) # Make predictions using the testing set diabetes_y_pred = regr.predict(diabetes_X_test) diabetes_y_pred pd.DataFrame(diabetes_y_test,diabetes_y_pred) # The coefficients print('Coefficients: \n', regr.coef_) # The mean squared error print("Mean squared error: %.2f" % mean_squared_error(diabetes_y_test, diabetes_y_pred)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))
"""Create a network proxy to sniff Tetris Friends network traffic. This script establishes a simple TCP network proxy between the Tetris Friends server and client, that can be used to sniff traffic, as well as inject traffic. Possible uses: * Record games as they are being played, to create a large corpus of game play data (eg. for training a ML model) * Generate live stats on player performance, and inject chat message summaries * Experiment with undocumented parts of the game Based on LiveOverflow's code here: https://github.com/LiveOverflow/PwnAdventure3/tree/master/tools/proxy For this to work you will need to route "sfs.tetrisfriends.com" to localhost in your /etc/hosts file. """ # import binascii import os import socket from threading import Thread from importlib import reload from collections import defaultdict, deque import tfparser as parser NULL_BYTE = b"\x00" # This is the IP for sfs.tetrisfriends.com TF_SERVER = "50.56.1.203" TF_PORT = 9339 # Use localhost by default, change this if running proxy on a different IP PROXY_IP = "0.0.0.0" # initialize a dictionary here to for the parser to use, since we are constantly # reloading the module we need some data to persist outside of the parser module PERSISTENT_DATA = {"fields": defaultdict(list), "game_started": False} class Proxy2Server(Thread): """This class creates a connection from the game server to the proxy.""" def __init__(self, host, port): """Initialize the connection to the server.""" super(Proxy2Server, self).__init__() self.game = None # game client socket not known yet self.port = port self.host = host self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.connect((host, port)) self.queue = deque() def run(self): """Receive packets from the server and run them through the parser module. When the start() method is called on a class instance, this code is run in a separate thread. """ buffer = b"" while True: # not sure if this should send one per packet or all at once while self.queue: packet = self.queue.popleft() print("sending packet to client:", packet) self.game.sendall(packet) data = self.server.recv(4096) if data: buffer += data while NULL_BYTE in buffer: packet, _, buffer = buffer.partition(NULL_BYTE) # could make this return if we should suppress process_packet(packet, "server") # forward data to game, do this after processing, in case we want to # suppress sending data later self.game.sendall(data) class Game2Proxy(Thread): """This class creates a connection from the game client to the proxy.""" def __init__(self, host, port): """Initialize the connection to the client.""" super(Game2Proxy, self).__init__() self.server = None # real server socket not known yet self.port = port self.host = host sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(1) # waiting for a connection self.game, _ = sock.accept() self.queue = deque() def run(self): """Receive packets from the client and run them through the parser module.""" buffer = b"" while True: while self.queue: packet = self.queue.popleft() print("sending packet to server:", packet) self.server.sendall(packet) data = self.game.recv(4096) if data: buffer += data while NULL_BYTE in buffer: packet, _, buffer = buffer.partition(NULL_BYTE) process_packet(packet, "client") # forward data to server, do this after processing, in case we want to # suppress sending data later self.server.sendall(data) class Proxy(Thread): """This class serves as a bridge between the client and server.""" def __init__(self, from_host, to_host, port): """Initialize the proxy.""" super(Proxy, self).__init__() self.from_host = from_host self.to_host = to_host self.port = port self.g2p = None self.p2s = None def run(self): """Create the two proxy connections and set up the bridge.""" while True: print("[proxy({})] setting up - waiting for connection".format(self.port)) self.g2p = Game2Proxy(self.from_host, self.port) # waiting for a client self.p2s = Proxy2Server(self.to_host, self.port) print("[proxy({})] connection established".format(self.port)) self.g2p.server = self.p2s.server self.p2s.game = self.g2p.game self.g2p.start() self.p2s.start() def process_packet(packet, origin): """Process a packet of data. This is a shared wrapper for processing data from both client and server. :param packet: bytes object representing binary data for one packet :param origin: string representing origin of packet, eg. "server" """ try: # print(origin, packet) reload(parser) parser.parse(packet, origin, PERSISTENT_DATA) except Exception as exception: print(f"Error processing {origin} packet:", packet[:32], "…") print(repr(exception)) def main(): """Run the script.""" proxy = Proxy(PROXY_IP, TF_SERVER, TF_PORT) proxy.start() # some simple input so user can inject commands, etc. while True: try: cmd = input("$ ") if cmd[:1] == "q": # sys.exit doesn't work, there's probably a better way to do this os._exit(0) # pylint: disable=W0212 elif cmd[:1] == "s": # send packet to server (from client) packet = cmd[1:].encode() + NULL_BYTE proxy.g2p.queue.append(packet) print("c->s:", packet) elif cmd[:1] == "c": # send packet to client (from server) packet = cmd[1:].encode() + NULL_BYTE proxy.p2s.queue.append(packet) print("s->c:", packet) except Exception as exception: print(exception) if __name__ == "__main__": main()
def bubbleSort(lst): for i in range(0, len(lst)): for j in range(0, len(lst)-i-1): if lst[j]> lst[j+1]: lst[j], lst[j+1] = lst[j+1], lst[j] test = [1,3,5,7,9,2,4,6,8,10,0,12,111,125,333,44] bubbleSort(test) print(test)
import pandas as pd import numpy as np def rep(dataframe, col, choice, value): "Tells about all the rows with which has an empty value for a particular column with an option to add / alter the values indicating empty values eg . NULL , NaN , , unknown etc and also allows a person to replace a given value choice is used to tell your choice whether to replace the value or not , value to enter a value you want to replace it with " a = [] print '****' maintainchar = ['unknown', 'Unknown', 'Null', 'null', '', '\0', np.nan] maintainint = [np.nan] count = 0 k = -1 reg = 0 ###print 'Do you want to replace value with something ' ##choice = True ## input choice here ##value=0 ## Enter the value here if(choice==False): if (dataframe[col].dtype == 'object'): ##print '1' ##dataframe[col].fillna(value, inplace=True) for i in dataframe[col].tolist(): count=count+1 if (i in maintainchar or i==np.nan): print 'Record No ', count, 'has a problem' reg = reg + 1 else: ##dataframe[col].fillna(value, inplace=True) for i in np.asarray(dataframe[col].tolist()): count = count + 1 ##print '4',i if (i in maintainint or np.isnan(i)): print 'Record No ', count, 'has a problem' reg = reg + 1 return reg else: li = [] ##dataframe[col].fillna(value,inplace=True) if (dataframe[col].dtype == 'object'): for i in dataframe[col].tolist(): ##k=k+1 ##print '2' count = count + 1 if (i in maintainchar): print 'Record No ', count, 'has a problem' li.append(value) ##dataframe.iloc[k][col] = value reg = reg + 1 else: li.append(i) else: li = [] ##dataframe[col].fillna(value, inplace=True) sd = np.asarray(dataframe[col].tolist()) for i in sd: count = count + 1 ##print i ##k = k + 1 if (i in maintainint or np.isnan(i)): print 'Record No ', count, 'has a problem' ##dataframe.loc[k,col] = value li.append(value) reg = reg + 1 else: li.append(i) dataframe[col].update(pd.Series(li)) return dataframe
""" ################################################################################ Name of problem: Return Nth to Last item in linked list Problem description: ################################################################################ """ """ ################################################################################ First attempt without looking up any answers ################################################################################ """ def nth_to_last(ll, n): if not ll: return 0 index = nth_to_last(ll.next, n) + 1 if index = n: return ll.data return index def kth_to_last(ll, k): p1 = ll.head p2 = ll.head # Move p1 k steps into the list while i < k: p1 = p1.next i += 1 # Move both until the first hits the end while p2 not None: p1 = p1.next p2 = p2.next # The second is k away from the end return p2.data """ ################################################################################ Solution inspired by looking at the solution(s) of others ################################################################################ """ if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "ALL TESTS PASSED!" print
""" ################################################################################ Name of problem: Print Power Set Problem description: Given an array print the power set of that array. The power set is defined to be the set of all subsets of S, including the empty set and S itself. ################################################################################ """ """ ################################################################################ First attempt without looking up any answers ################################################################################ """ def print_power_set(arr): """This function takes an array and returns an array that is the power set of the given array. This solution assumes that there are no duplicate items in the set. >>> print_power_set([1, 2, 3]) [[], [1, 2, 3], [1], [2], [3], [1, 2], [1, 3] [2, 3]] """ # The power set will always contain the empty set and the set itself power_set = [[], arr] width = 1 for i in range(len(a)-width): for j in range(len(a)-width): print a[i:i+width] + [a[j+width]] print power_set def print_power_set_recursive(arr, width=0, power_set=[]): """Recursive solution to print power set. >>> print_power_set_recursive([1, 2, 3]) [[], [1], [2], [3], [1, 2], [1, 3] [2, 3], [1, 2, 3]] """ if width + 1 == len(arr): power_set.append(arr) print power_set return if width == 0: power_set.append([]) elif width == 1: for item in arr: power_set.append([item]) else: for i in range(len(arr) - width): for j in range(len(arr) - width): power_set.append(arr[i:i+width] + [arr[j+width]]) # recursive call here print_power_set_recursive(arr, width+1, power_set) """ ################################################################################ Solution inspired by looking at the solution(s) of others ################################################################################ """ def powerset1(s): """Iteratively with a list comprehension >>> powerset1([1, 2, 3]) [[], [1], [2], [3], [1, 2], [1, 3] [2, 3], [1, 2, 3]] """ result = [[]] for ss in s: new_subset = [subset + [ss] for subset in result] result.extend(new_subset) return result def powerset2(s, new=[]): """Recursively >>> powerset2([1, 2, 3]) [[], [1], [2], [3], [1, 2], [1, 3] [2, 3], [1, 2, 3]]""" if s == []: return new else: result = [] for ss in powerset2(s[1:], new+[s[0]]): result.append(ss) for ss in powerset2(s[1:], new): result.append(ss) return result def powerset3(orig, newset=[]): """By making a generator object >>> list(powerset3([1, 2, 3])) [[], [1], [2], [3], [1, 2], [1, 3] [2, 3], [1, 2, 3]]""" if orig == []: yield newset else: for s in powerset3(orig[1:], newset+[orig[0]]): yield s for s in powerset3(orig[1:], newset): yield s if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "ALL TESTS PASSED!" print
# -*- coding: utf-8 -*- """ Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. Explanation: even Fibonacci numbers are separated by exactly 2 odd ones. Proof is by induction. It's true with the first numbers: 2, 3, 5, 8. Assume that it's true till i-th number that is even. Then (i-1)th one is odd. (i+1)th one is (i-1)th + i-th and then odd. And then (i+2)th one is the sum of the i-th and the (i+1)th one that should be odd too. The (i+3)th one is the sum of 2 odd numbers, which is then even. With this, we can accelate a bit the computation. Suppose that we have a, b are the (i-1)th and i-th Fibonacci number where b is even. The next numbers are: (i-1)th: a i-th: b (i+1)th: a + b (i+2)th: a + 2b (i+3)th: 2a + 3b So if we remember (i+2)th and (i+3) as a', b', we can compute the next ones """ def fibonacci_pair(a, b): return a + 2*b, 2*a + 3*b def sum_even_fibonacci(iLimit): a = 1 b = 2 aSum = 0 while b <= iLimit: aSum += b a, b = fibonacci_pair(a, b) return aSum def main(): print('Hello Problem 2') print(sum_even_fibonacci(4000000)) if __name__ == '__main__': main()
from abc import ABCMeta, abstractclassmethod class Instrumento(metaclass=ABCMeta): @abstractclassmethod def afinar(cls): pass @abstractclassmethod def tocar(cls): pass @abstractclassmethod def tocarEn(cls): pass class Guitarra(Instrumento): def __init__(self, afinar,tocar): self.afinar= afinar self.tocar = tocar def afinar(self): return "Afinando la guitarra" def tocar(self): return "tocando la guitarra" class Bajo(Instrumento): def __init__(self, afinar,tocar): self.afinar= afinar self.tocar = tocar def afinar(self): return "Afinando el bajo" def tocar(self): return "tocando el bajo" class Violin(Instrumento): def __init__(self, afinar,tocar): self.afinar= afinar self.tocar = tocar def afinar(self): return "Afinando el violin" def tocar(self): return "tocando el violin " class Persona(): def __init__(self, nombre): self.nombre=nombre def presentar(self,nombre): return " hola mi nombre es "+ self.nombre
#!/usr/lib/python3 import random # 从序列的元素中随机挑选一个元素 print(random.choice(range(10))) # 从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1 for i in range(10): print("randrange(0, 1000, 2) : ", random.randrange(0, 1000, 2)) for i in range(10): print("randrange(0, 1000, 3) : ", random.randrange(0, 1000, 3)) # 随机生成下一个实数,它在[0,1)范围内。 print(random.random()) # 改变随机数生成器的种子seed。如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed。 random.seed(10) print(random.random()) print(random.random()) # 将序列的所有元素随机排序 lst = [20, 16, 10, 5] random.shuffle(lst) print(lst) random.shuffle(lst) print(lst) # 随机生成下一个实数,它在[x,y]范围内。 print(random.uniform(10, 20))
#!/usr/bin/env python ''' 基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。 紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用, 这个方法的返回值将被赋值给as后面的变量。 当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。 ''' import time class Sample: def __enter__(self): return self def __exit__(self, type, value, trace): print("trace:", trace) print("type:", type) print("value:", value) def do_something(self, exp=True): if exp: 1 / 0 else: pass # 只执行一次exit with Sample() as sample: sample.do_something(False) sample.do_something(False) sample.do_something(False) # 抛异常 with Sample() as sample: sample.do_something()
import turtle t = turtle.Turtle() def drawT(width,height): ''' draw a T assume turtle facing east (0), and leave it facing east assume pen is down no assumptions about position. ''' t.forward (width) t.backward (width/2) t.right (90) t.forward (height) t.left(90) drawT(50,100)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 1 17:27:12 2019 @author: BlackBox """ def robotCheer(): an_letters = "aefhilmnorsx" word = input('Robot cheer! Enter a word: ') times = input('Enthusiam level (1-10): ') times = int(times) for letter in word: if letter in an_letters: print('Give me an {}! {}'.format(letter.upper(),letter.upper())) else: print('Give me a {}! {}'.format(letter.upper(),letter.upper())) print('What does that spell???') for i in range(0,times): print(word.upper(),'!!!!!') def guess(cube,verbose=False): cube = int(cube) output = 0 for i in range(0,cube): if i**3 == cube: output = i if output != 0: print('{} is the cube root of {}'.format(output,cube)) else: if verbose == True: print('No cube root of {} found'.format(cube)) guess(8) guess(16) guess(17) def guessApprox(cube,error=.01,verbose=False,attempts=10000): cube = int(cube) isExact = False error = float(error) for i in range(0,cube): if i**3 == cube: isExact = True output = i if isExact == True: print('{} is the cube root of {}'.format(output,cube)) else: increment = error/10 for i in range(0,attempts,increment):#increment by float causes error if (abs(i**3)-(cube)) < error: print('{} is approx the cube root of {} with {} error tolerance'.format(i,cube,increment)) else: print('Failed within {} attempts'.format(attempts)) guessApprox(100)
#!/usr/bin/env python3 #Foreign Currency #KBowen import locale gblmoney = [0.0, 0.0, 0.0, 0.0, 0.0] #keep ctry = ["Euros (EUR)", "British Pounds (GBP)", "Yen (YEN)", "Hockey Money (CAD)", "Rubles (RUB)"] #keep def doValuation(): global ctry, gblmoney qty = 0 cval = 0.0 grandtotal = 0.0 totcunits = [0, 0, 0, 0, 0] #list of 5 values totcval = [0.0, 0.0, 0.0, 0.0, 0.0] choice = getChoice() while choice!=0: if choice!=9: qty = getQty(ctry[choice-1]) cval = qty * gblmoney[choice-1] totcunits[choice-1] = totcunits[choice-1] + qty totcval[choice-1] = totcval[choice-1] + cval grandtotal += cval print(ctry[choice-1] + " has a value of %s " %locale.currency(cval,grouping=True)) elif choice ==9: getRates() else: print("Unknown entry: How did we get here?") print() choice = getChoice() print("Purchase Summary: ") for i in range(0,5): print (ctry[i] + ": " + str(totcunits[i]) + " units for a value of: %s" %locale.currency(totcval[i],grouping=True)) print("Today's grand total is %s: "%locale.currency(grandtotal,grouping=True)) def getChoice(): choice = -1 while (choice < 0 or (choice > 5 and choice !=9)): try: choice = int(input("Select currency for valuation (1=EUR, 2=GBP, 3=JPY, 4=CAD, 5=RUB, 9=New Rates, 0=Quit): ")) if (choice < 0 or (choice > 5 and choice !=9)): print("Unknown operation: 1-5, 9 or 0 only") except ValueError: print("Illegal input, integers 0-5 or 0 only") return choice def getQty(prompt): sentinel = -1 while sentinel < 0: try: sentinel = int(input("How many " +prompt + " are you buying?: ")) if(sentinel<=0): print("Positive values only.") except ValueError: print("Illegal Entry: Postive numbers only please.") return sentinel def getRates(): global gblmoney, ctry print("Please enter the currency rate per US $ for the following currencies\n") for i in range(0,5): gblmoney[i] = getOneRate(ctry[i]) def getOneRate(prompt): sentinel = -1 while sentinel < 0: try: sentinel = float(input(prompt + ": ")) if(sentinel<=0): print("Positive values only.") except ValueError: print("Illegal Entry: Postive numbers only please.") return sentinel def main(): result = locale.setlocale(locale.LC_ALL, '') if result == "C" or result.startswith("C/"): locale.setlocale(locale.LC_ALL, 'en_US') print("Welcome to the Currency Calculator") print() getRates() doValuation() print("Thanks for using the calculator") if __name__ == "__main__": main()
import turtle,operator wid = 20#柱状宽度 divi = 0.5#设置单位柱状高度与单词 k = 1300#屏幕长 h = 700#屏幕宽 x1 = 600#x轴长 def post(x,word):#绘制位置,绘制单词(数量,单词) turtle.penup() turtle.goto(x,-h/2 + 100) turtle.pendown() turtle.color("red") turtle.seth(90) turtle.fd(word[0] * divi) turtle.write(word[0]) turtle.seth(0) turtle.fd(wid) turtle.seth(-90) turtle.fd(word[0] * divi) turtle.penup() turtle.fd(15) turtle.seth(180) turtle.fd(wid) turtle.pendown() turtle.write(word[1]) def graphy(words): turtle.title("词词频统计") turtle.setup(k,h,0,0)#设置屏幕大小 #绘制x,y轴 turtle.color("blue") turtle.pensize(5) turtle.penup() turtle.seth(180) turtle.fd(k/2 - 100) turtle.seth(-90) turtle.fd(h/2 - 100) turtle.pendown() turtle.seth(0) turtle.fd(x1)#x轴长度 turtle.write("x") turtle.seth(180) turtle.fd(x1) turtle.seth(90) turtle.fd(300)#y轴长度 turtle.write("y") for i in range(10):#控制绘制出排名前几的单词 post(-k/2 + 100 + wid + wid * i * 2,words[-(i + 1)]) turtle.done() def main(): filename = input("请输入文件名称 : ").strip() f1 = open(filename,"r") str = [] for line in f1: for i in line[:-1]: if i in "~@#$%^&*()_-+=<>?/,.:;{}[]|\'1234567890""" : line = line[:-1].replace(i,' ') str = str + line[:-1].lower().split() count = {} for word in str: count.setdefault(word,0) count[word] = count[word] + 1 #pairs = list(count.items()) #words = [[x,y]for (y,x)in pairs] #import opeartor word.sort(key = operator.itemgetter(1)) words = [[x,y]for (y,x)in list(count.items())] words.sort() graphy(words) main() #artical.txt #当改变一个数值后关系到多个表达式,则用变量表示
l1 = [-2, 11, 44, 55, -44, 22, -15, 88, -80, 10] for x in l1: if x > 0: print("Number is Positive: ", x) for x in l1: if x < 0: print("Number is Negative: ", x)
''' Positive Number ''' for x in range(-20, 15): if x > 0: print("Positive Number= ", x)
#### Armstrong Number ##### num=int(input("Enter a number= ")) def check_armstrong(num): order = len(str(num)) sum= 0 original = num while num> 0: digit = num% 10 sum+= digit ** order num= num//10 if sum == original: return True print("Number is armstrong ") else: return False print("Number is not armstrong ") if check_armstrong(num): print("Number is armstrong") else: print("Number is not armstrong")
'''Q.6 max no.of array''' array = [11, 22, 33, 88, 44, 100, 50, 99] max=array[0] n=len(array) for i in range(1,n): if array[i]>max: max=array[i] print(max) '''minimum no.of array''' ''' min=array[0] n=len(array) for i in range(1,n): if array[i]<min: min=array[i] print(min) '''
'''69. Convert a list of Tuple into Dictionary''' x=[("Sachin",10),("Virat",18),("M.S.D",7),("Ro-Hit",45)] print(x) # print(type(x)) y = dict(x) print(dict(x)) # print(type(y)) # def dic(x): # return(dict(x)) # # x=[("Sachin",10),("Virat",18),("M.S.D",7),("Ro-Hit",45)] # print(dic(x))
class math(): def __init__(self,inp1,inp2): self.y=inp1 self.z=inp2 def mult1(self): w=self.y*self.z print('multuplication=',w) b=math(2,6) b.mult1()
# coding=utf-8 # 114. 二叉树展开为链表 https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: None Do not return anything, modify root in-place instead. """ def do_post_order_traversal(node): if node: do_post_order_traversal(node.right) do_post_order_traversal(node.left) if not self.pre: self.pre = node else: node.right = self.pre self.pre = node node.left = None self.pre = None do_post_order_traversal(root) return root if __name__ == '__main__': root=TreeNode(1) l1 = TreeNode(2) root.left = l1 l1.left = TreeNode(3) l1.right = TreeNode(4) r1 = TreeNode(5) root.right = r1 r1.right = TreeNode(6) s = Solution() s.flatten(root) print root.val
# 112. 路径总和 https://leetcode-cn.com/problems/path-sum/ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ def do_has_path_sum(node,sum): if node is not None: self.list.append(node.val) temp = sum - node.val if temp == 0 and node.left is None and node.right is None: self.result = True do_has_path_sum(node.left,temp) do_has_path_sum(node.right,temp) self.list.pop() self.list = [] self.result = False do_has_path_sum(root,sum) return self.result if __name__ == '__main__': s = Solution() r = TreeNode(-2) r.right = TreeNode(-3) print s.hasPathSum(r,-5)
# 96 https://leetcode-cn.com/problems/unique-binary-search-trees/ class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ list = [1,1,2] if n == 0 or n == 1: return 1 for i in range(2,n): temp = 0 j = 0 while j <= i: temp += list[j]*list[i - j] j += 1 list.append(temp) return list[n] if __name__ == '__main__': s = Solution() print s.numTrees(3)
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ def inorder(node): if node: rs = True if node.left: rs = rs and inorder(node.left) if self.pre is None: self.pre = node.val else: rs = rs and (node.val > self.pre) self.pre = node.val if node.right: rs = rs and inorder(node.right) return rs return True self.pre = None return inorder(root)
"""Client program to communicate with server over tcp It firstly handshakes the server, then sends one encrpted message and closes connection sources: https://docs.python.org/3/library/socket.html # pip install pycryptodome """ __author__ = "Kamil Skrzypkowski, Andrzej Mrozik" import socket import sys from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP # Create key and public key for client key = RSA.generate(1024) private_key = PKCS1_OAEP.new(key) # Setting up socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: client.connect((sys.argv[1], 8080)) except IndexError: client.connect(('0.0.0.0', 8080)) # Handshaking client.send(key.publickey().exportKey()) server_key = RSA.importKey(client.recv(4096)) server_key = PKCS1_OAEP.new(server_key) print("Handshaking - DONE") # Message to send print("Type your message") msg = input(">") msg = server_key.encrypt(msg.encode()) client.send(bytes(msg)) client.close()
num = int(input("Enter a number: ")) a = num % 10 b = num % 100 // 10 c = num // 100 res = a * 100 + b * 10 + c print(res) # Добрый день Николай. Я сделала еще вариант для четырехзначного числа, для проверки себя, что я разобралась. num = int(input("Enter a number: ")) a = num // 1000 b = num // 100 % 10 c = num // 10 % 10 d = num % 10 my = d * 1000 + c * 100 + b * 10 + a print(my)
""" Student code for Word Wrangler game """ import urllib2 import codeskulptor import poc_wrangler_provided as provided WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative. """ no_duplicates = [] num = 0 while num <= len(list1) - 1: no_duplicates.append(list1[num]) i = 1 if num < len(list1) - 1: while list1[num] == list1[num + i]: i += 1 if num + i > len(list1) - 1: break num += i return no_duplicates def intersect(list1, list2): """ Compute the intersection of two sorted lists. Returns a new sorted list containing only elements that are in both list1 and list2. This function can be iterative. """ if len(list1) == 0 or len(list2) == 0: return [] elif list1[0] > list2[-1] or list1[-1] < list2[0]: return [] else: if(list1[0] <= list2[0]): first_list = list1 second_list = list2 else: first_list = list2 second_list = list1 intersect_list = [] num = 0 index = 0 while num < len(second_list) and index < len(first_list): while second_list[num] > first_list[index]: index += 1 if index > len(first_list) - 1: break if index < len(first_list): if second_list[num] == first_list[index]: intersect_list.append(second_list[num]) index += 1 num += 1 return intersect_list # Functions to perform merge sort def merge(list1, list2): """ Merge two sorted lists. Returns a new sorted list containing those elements that are in either list1 or list2. This function can be iterative. """ if len(list1) == 0: return list2 elif len(list2) == 0: return list1 elif list1[0] <= list2[0]: first_list = list1 second_list = list2 else: first_list = list2 second_list = list1 sorted_list = [] index = 0 for num1 in range(len(second_list)): if index < len(first_list): while first_list[index] < second_list[num1]: sorted_list.append(first_list[index]) index += 1 if index > len(first_list) -1: break sorted_list.append(second_list[num1]) if index < len(first_list): sorted_list = sorted_list + first_list[index:] return sorted_list def merge_sort(list1): """ Sort the elements of list1. Return a new sorted list with the same elements as list1. This function should be recursive. """ if len(list1) <= 1: return list1 if len(list1) == 2: return merge(list1[:1], list1[1:]) else: list11 = merge_sort(list1[0:(len(list1)/2)]) list12 = merge_sort(list1[len(list1)/2:]) return merge(list11, list12) # Function to generate all strings for the word wrangler game def gen_all_strings(word): """ Generate all strings that can be composed from the letters in word in any order. Returns a list of all strings that can be formed from the letters in word. This function should be recursive. """ if len(word) == 0: return [''] if len(word) == 1: return ['', word] else: first = word[0] rest = word[1:] rest_strings = gen_all_strings(rest) all_possibles = [] for item in rest_strings: for ind in range(len(item)+1): new = item[:ind] + first + item[ind:] all_possibles.append(new) return rest_strings + all_possibles # Function to load words from a file def load_words(filename): """ Load word list from the file named filename. Returns a list of strings. """ url = codeskulptor.file2url(filename) doc = urllib2.urlopen(url) words = [] for line in doc.readlines(): words.append(line[:-1]) return words def run(): """ Run game. """ words = load_words(WORDFILE) wrangler = provided.WordWrangler(words, remove_duplicates, intersect, merge_sort, gen_all_strings) provided.run_game(wrangler) # Uncomment when you are ready to try the game run()
# coding=utf-8 import os # 生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用range(1, 11): print range(1, 11) # 生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?方法一是循环: L = [] for x in range(1, 11): L.append(x * x) print L # 列表生成式则可以用一行语句代替循环生成上面的list: print [x * x for x in range(1, 11)] # 还可以使用两层循环,可以生成全排列: print [m+n for m in 'ABC' for n in 'XYZ'] # 列出当前目录下的所有文件和目录名,可以通过一行代码实现: print [d for d in os.listdir(".")]
#coding=utf-8 # 高阶函数英文叫Higher-order function。 # 函数本身也可以赋值给变量,即:变量可以指向函数。 f = abs print f(-10) # 函数名也是变量 # 那么函数名是什么呢?函数名其实就是指向函数的变量!对于abs()这个函数,完全可以把函数名abs看成变量,它指向一个可以计算绝对值的函数! # 传入函数 def add(x, y, f): return f(x) + f(y) print add(-5, 6, abs)
# ‐*‐ coding: utf‐8 ‐*‐ valorA = input("Introduce valor A: ") valorB = input("Introduce valor B: ") valorC = input("Introduce valor C: ") if (valorA/valorB > 30): print ((valorA/valorC*valorB)**3) elif (valorA/valorB <= 30): suma = 0 for i in range(2, 31, 2): suma = i**2 print suma
# ‐*‐ coding: utf‐8 ‐*‐ mares1 = ["mediterraneo", "cantabrico", "baltico", "adriatico", "tirreno", "egeo"] mares2 = ["rojo", "muerto", "caspio", "negro", "arabigo", "sulu"] mares = ["mediterraneo", "cantabrico", "baltico", "adriatico", "tirreno", "egeo", "rojo", "muerto", "caspio", "negro", "arabigo", "sulu"] print mares1 print mares2 print mares print mares1[1] + " " + mares1[2] + " " + mares1[3] print mares1.index("egeo") print mares2[4:6] print mares2.index("caspio") print mares.index("caspio")
# ‐*‐ coding: utf‐8 ‐*‐ def getElemento(l, i): try: return l[i] except IndexError: return None lista = [] elementos = input("Introduce número de elementos: ") for i in range(elementos): lista.append(raw_input("Elemento "+str(i)+": ")) indice = input("Introduce el índice: ") print getElemento(lista, indice)
# ‐*‐ coding: utf‐8 ‐*‐ class Termo: def __init__(self, cantidadCafe): if (isinstance(cantidadCafe, (int, float, long))): if (cantidadCafe >= 0 and cantidadCafe <= 10): self.cantidadCafe = cantidadCafe self.isFull = False else: raise TypeError("El dígito debe estar comprendido entre 0 y 10 (inclusives)") else: raise TypeError("Debes introducir un dígito") def rellenar(self): if (self.cantidadCafe < 10): self.cantidadCafe += 1 else: raise TypeError("¡Cuidado!¡Se desbordará!") def beber(self): if (self.cantidadCafe > 0): self.cantidadCafe -= 1 else: raise TypeError("¡El termo está vacío!")
import pygame import random import sys from pygame.locals import * level = input('Level[0/1/2/3]: ') #Create the objects class Player(pygame.sprite.Sprite): def __init__(self): super(Player, self).__init__() #load the plane image self.image = pygame.image.load('plane.png').convert() #remove the background of the image self.image.set_colorkey((255, 255, 255), RLEACCEL) self.rect = self.image.get_rect() class Bullet(pygame.sprite.Sprite): def __init__(self): super(Bullet, self).__init__() self.image = pygame.image.load('bullet.png').convert() self.image.set_colorkey((255, 255, 255), RLEACCEL) #define the generate position of bullets self.rect = self.image.get_rect(center=(470, random.randint(0, 700))) #change the speed according to the level user choosed if level == 0: self.speed = random.randint(1, 2) if level == 1: self.speed = random.randint(2, 3) if level == 2: self.speed = random.randint(3, 6) if level == 3: self.speed = random.randint(5, 7) def update(self): #make the bullet move from left to right self.rect.move_ip(-self.speed, 0) #to avoid the bullet vanished immediately when reaching the screen boundary #the bullet image will be removed after the whole image crossed the right border #of the screen if self.rect.right < 0: self.kill() class Present(pygame.sprite.Sprite): def __init__(self): super(Present, self).__init__() self.image = pygame.image.load('Present.png').convert_alpha() self.rect = self.image.get_rect(center=(random.randint(0, 450),0)) self.speed = random.randint(1, 3) def update(self): #make the supplies drop vertically with a random speed self.rect.move_ip(0, self.speed) class Cloud(pygame.sprite.Sprite): def __init__(self): super(Cloud, self).__init__() #convert_alpha() works when the background is transparent self.image = pygame.image.load('cloud.png').convert_alpha() self.rect = self.image.get_rect(center = (470,random.randint(0,700))) def update(self): self.rect.move_ip(-1,0) if self.rect.right < 0: self.kill() #define the main game into a function to make it recallable def run_game(): #Initialize the game pygame.init() #Set a screen of 450*700 and filled it with black screen = pygame.display.set_mode((450, 700),0,32) background = pygame.Surface(screen.get_size()) background.fill((135, 208, 240)) #Write a title pygame.display.set_caption("Get as much supply as you can :)") #Load a game over image game_over = pygame.image.load('gameover.png') #Create custom events for adding new objects periodically ADDENEMY = pygame.USEREVENT + 1 #Adjust the time interval of generating the bullets according to the level if level == 0: pygame.time.set_timer(ADDENEMY, 500) elif level == 3: pygame.time.set_timer(ADDENEMY, 150) else: pygame.time.set_timer(ADDENEMY, 250) ADDPRESENT = pygame.USEREVENT + 2 pygame.time.set_timer(ADDPRESENT, 1000) ADDCLOUD = pygame.USEREVENT + 3 pygame.time.set_timer(ADDCLOUD,2000) #Create a plane(player) player = Player() #Set the initial score score = 0 #Set the initial player state hit = False #Create different group for different object bullet_list = pygame.sprite.Group() present_list = pygame.sprite.Group() clouds_list = pygame.sprite.Group() all_sprites_list = pygame.sprite.Group() all_sprites_list.add(player) clock = pygame.time.Clock() #The main loop #Checking the player state while not hit: #control the frame time clock.tick(60) #trigger the custom events, add objects to the world for event in pygame.event.get(): if event.type == ADDENEMY: new_item = Bullet() bullet_list.add(new_item) all_sprites_list.add(new_item) elif event.type == ADDPRESENT: new_present = Present() present_list.add(new_present) all_sprites_list.add(new_present) elif event.type == ADDCLOUD: new_cloud = Cloud() clouds_list.add(new_cloud) all_sprites_list.add(new_cloud) #Blit the screen screen.blit(background, (0, 0)) #Get the mouse position position = pygame.mouse.get_pos() #Relate the mouse position to the plane position player.rect.x = position[0] player.rect.y = position[1] player.update() all_sprites_list.update() #blit all of the objects for all in all_sprites_list: screen.blit(all.image, all.rect) #Check for collision #if player and bullets collides #kill the player & jump out of the main loop if pygame.sprite.spritecollideany(player, bullet_list): player.kill() hit = True #if player and supplies collides, add 1 point to the score variable if pygame.sprite.spritecollide(player, present_list, True): score += 1 #we don't want any interaction between clouds and player, so we don't test the #collides between them #set the font of the score board score_font = pygame.font.Font(None, 36) score_text = score_font.render('Score: '+ str(score), True, (128, 128, 128)) #set the position of the score board text_rect = score_text.get_rect() text_rect.topleft = [10, 10] #blit the score board screen.blit(score_text, text_rect) #update the whole screen pygame.display.flip() #blit the gameover image and the final score font = pygame.font.Font(None, 45) text1 = font.render('Score: '+ str(score), True, (255, 0, 0)) text1_rect = text1.get_rect() text1_rect.centerx = screen.get_rect().centerx text1_rect.centery = screen.get_rect().centery + 60 text2 = font.render('Press r to restart', True, (255, 0, 0)) text2_rect = text2.get_rect() text2_rect.centerx = screen.get_rect().centerx text2_rect.centery = screen.get_rect().centery + 100 screen.blit(text1, text1_rect) screen.blit(text2, text2_rect) screen.blit(game_over, (0, 0)) run_game() while 1: for event in pygame.event.get(): #check for the event that player wants to quit the game if event.type == pygame.QUIT: sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit() #check for the event(press r key) that player wants to restart the game if event.key == K_r: run_game() pygame.display.update()
#!/usr/bin/env python #PROBLEM # ================ #A string is simply an ordered collection of symbols selected from some alphabet and formed into a word; the length of a string is the number of symbols that it contains. #An example of a length 21 DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T') is "ATGCTTCAGAAAGGTCTTACG." #Given: A DNA string s of length at most 1000 nt. #Return: Four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s. #Sample Dataset #AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC #Sample Output #20 12 17 21 #================ #CODE s = input("Enter your DNA sequence: ") acount = 0 ccount = 0 gcount = 0 tcount = 0 for nt in s: if nt == "A": acount +=1 elif nt == "C": ccount +=1 elif nt == "G": gcount +=1 elif nt == "T": tcount +=1 print(acount, ccount, gcount, tcount)
from battleship import BattleShip import random class Game: def __init__(self, boardSize, player1Name, player2Name): self.player1 = BattleShip(boardSize) self.player2 = BattleShip(boardSize) self.player1Name = player1Name self.player2Name = player2Name self.boardSize = boardSize def fillBoards(self): if "CPU" in self.player1Name: print("Placing ships for {}".format(self.player1Name)) self.player1.placeAllShipsComputer() else: print("{}, please place your ships".format(self.player1Name)) self.player1.placeAllShipsHuman() if "CPU" in self.player2Name: print("Placing ships for {}".format(self.player2Name)) self.player2.placeAllShipsComputer() else: print("{}, please place your ships".format(self.player2Name)) self.player2.placeAllShipsHuman() def getTargetHuman(self): valid = False while not valid: try: x,y = input("Enter target in format x,y: ").split(",") x = int(x) y = int(y) except: print("Invalid co-ordinates. Please try again") else: valid = True return x,y def getTargetComputer(self, player): valid = False if player.firstHitMade: print("\nMaking AI Move") return player.getBestLocation() else: x = random.randint(0,self.boardSize-1) y = random.randint(0,self.boardSize-1) return [x,y] def playGame(self): self.fillBoards() player1 = True won = False c1, c2 = 0, 0 while not won: if player1: print("{}'s turn.".format(self.player1Name)) self.player2.recalculateHitProbabilities() move = False while not move: if "CPU" in self.player1Name: x,y = self.getTargetComputer(self.player2) else: x,y = self.getTargetHuman() move = self.player2.hitTarget(x,y) player1 = False self.player2.displayBoard() if self.player2.shipCount == 0: print("{} has won".format(self.player1Name)) won = True c1+=1 else: print("{}'s turn.".format(self.player2Name)) self.player1.recalculateHitProbabilities() move = False while not move: if "CPU" in self.player2Name: x,y = self.getTargetComputer(self.player1) else: x,y = self.getTargetHuman() move = self.player1.hitTarget(x,y) player1 = True self.player1.displayBoard() if self.player1.shipCount == 0: print("{} has won".format(self.player2Name)) won = True c2+=1 print("Moves made Player 1 : {} and Player 2: {}".format(c1, c2)) return max(c1, c2)
my_first_game = [' - ',' - ',' - ', ' - ',' - ',' - ', ' - ',' - ',' - ' ] #first create a game bord # switsh turn of the user and input the value # select the winner of the game # game_is_going = True num = ' X ' def the_board(): print(my_first_game[0] +'|'+ my_first_game[1]+'|'+my_first_game[2]+ '\n' +my_first_game[3]+'|'+ my_first_game[4]+'|'+my_first_game[5]+ '\n' +my_first_game[6]+'|'+ my_first_game[7]+'|'+my_first_game[8]) return def input_number(): global num global game_is_going while game_is_going: user_input = input('To run the game...\nTo exit enter "q" or "quit"....\ninput number from 1-9:') if user_input == 'q' or 'quit' : quit() # check wether user input between 1-9 user_in = int(user_input)-1 if user_in in [0,1,2,3,4,5,6,7,8]: if my_first_game[user_in] == ' O ' or my_first_game[user_in] == ' X ': print("\n\tThe number u entered has already a value.......select another number.......\n") # if number has already a value input_number() else: my_first_game[user_in] = num elif user_in not in [0,1,2,3,4,5,6,7,8]: print('\n\tThe value u entered not found........select another value.........\n') input_number() the_board() switch_user() check_if_win() return # switch the turn of users....... def switch_user(): global num if num == ' X ': num = ' O ' elif num == ' O ': num = ' X ' return def check_if_win(): global game_is_going # ============================================================================= # # ============================================================================= column =[ my_first_game[0] == my_first_game [1] == my_first_game[2] !=' - ', my_first_game[3] == my_first_game[4]== my_first_game[5] !=' -' , my_first_game[6] == my_first_game [7] == my_first_game[8] !=' - ' , ] row = [ my_first_game[0] == my_first_game[3] == my_first_game[6] !=' - ' , my_first_game[1] == my_first_game[4] == my_first_game[7] !=' - ', my_first_game[2] == my_first_game[5] == my_first_game[8] !=' - ', ] diagonal = [my_first_game[0] == my_first_game[4] == my_first_game[8] !=' - ' , my_first_game[2] == my_first_game[4] == my_first_game[6] !=' - ' ] # ============================================================================= # # ============================================================================= # find the winner name if num == ' X ': winner = ' O ' elif num == ' O ': winner = ' X ' # just for finding winnner of the game above 5 lines # ============================================================================= # # ============================================================================= for column_ in column : if column_ == True: print('\n', winner ,'winner.',) game_is_going = False for row_ in row : if row_ == True: print('\n', winner ,'winner.',) game_is_going = False for diagonal_ in diagonal : if diagonal_ == True : print('\n', winner ,'winner.',) game_is_going = False return def check(): return def run_game(): the_board() input_number() return run_game()
class Book(): def __init__(self, title, author, pages): self.title = title self.author = author self.pages = pages # Special methods to convert a book to string def __str__(self): return f"{self.title} by {self.author}" # Special methods to return the length of a book def __len__(self): return self.pages # Special methods to delete a book def __del__(self): print("A book object has been deleted") def main(): book = Book("Python rocks", "John", 200) print(book, ",", len(book), "pages") del book if __name__ == "__main__": main()
import math import collections import string def vol(rad): return 4.0 / 3.0 * math.pi * rad**3 def ran_check(num, low, high): return num in range(low, high + 1) def up_low(str): letters = list(str) lowercount = 0 uppercount = 0 for letter in letters: if letter.islower(): lowercount += 1 elif letter.isupper(): uppercount += 1 print("Nb upper case letters:", uppercount) print("Nb lower case letters:", lowercount) def unique_list(l): a = [] for x in l: if x not in a: a.append(x) return a def multiply(numbers): product = 1 for num in numbers: product *= num return product def palindrome(s): return s[::-1] == s def pangram(str1, alphabet=string.ascii_lowercase): trimedstr = str1.replace(" ", "") trimedstr = trimedstr.lower() setstr = set(trimedstr) return len(setstr) == len(alphabet) def main(): print("Write a function that computes the volume of a sphere given its radius") print("rad = 3 ->", vol(3)) print("\nWrite a function that checks whether a number is in a given range (Inclusive of high and low).") print("ran_check(3, 4, 6) ->", ran_check(3, 4, 6)) print("ran_check(3, 3, 6) ->", ran_check(3, 3, 6)) print("ran_check(6, 4, 6) ->", ran_check(6, 4, 6)) print("\nWrite a function that accepts a string and calculate the number of upper case") print("letters and lower case letters.") st = "Hello Mr. Rogers, how are you this fine Tuesday?" print(st) up_low(st) print("\nWrite a function that takes a list and returns a new list with unique elements of the first list.") print("[1,1,1,1,2,2,3,4,4,4,4,5,5,5,5] ->", unique_list([1,1,1,1,2,2,3,4,4,4,4,5,5,5,5])) print("\nWrite a function to multiply all the numbers in a list.") print("[1, 2, 3, -4] ->", multiply([1, 2, 3, -4])) print("\nWrite a function that checks whether a passed string is a palindrome or not.") print("helleh", palindrome("helleh")) print("hello", palindrome("hello")) print("\nWrite a function to check whether a string is pangram or not.") print("The quick brown fox jumps over the lazy dog", pangram("The quick brown fox jumps over the lazy dog")) print("The quick brown fox jumps over the dog", pangram("The quick brown fox jumps over the dog")) if __name__ == "__main__": main()
# Using a default argument def myfunction(name='NoName'): """Hello name Args: name (string): name Returns: string: Hello name """ return "Hello " + name def main(): print("== Print doc on the insert function ==") help([1, 2].insert) print("== Print doc on myfunction ==") help(myfunction) print("== Function returning a string ==") print(myfunction("Sam")) print(myfunction()) print("Ternary if operator (a ? b : c)") a = False print('Hello' if a else 'Goodbye') if __name__ == "__main__": main()
if __name__ == "__main__": num = 15 print(f"Hexadecimal: {num} => {hex(num)}") print(f"Binary: {num} => {bin(num)}") print(f"pow(2, 4): {pow(2, 4)}") print(f"pow(2, 4, 3) (last number is a modulo): {pow(2, 4, 3)}") print(f"abs(-10): {abs(-10)}") print(f"round(3.2): {round(3.2)}") print(f"round(3.7): {round(3.7)}") print(f"round(3.14159, 2): {round(3.14159, 2)}")
import datetime if __name__ == "__main__": t = datetime.time(5, 25, 1) print(t) print("") print("datetime.time.min:", datetime.time.min) print("datetime.time.max:", datetime.time.max) print("datetime.time.resolution:", datetime.time.resolution) print("") today = datetime.date.today() print("Today:", today) print("Today:", today.timetuple()) print("datetime.date.min:", datetime.date.min) print("datetime.date.max:", datetime.date.max) print("datetime.date.resolution:", datetime.date.resolution) print("") d1 = datetime.date(2019, 1, 31) d2 = d1.replace(year=1990) print("d1", d1) print("d2", d2) delta = d1 - d2 print("d1 - d2:", delta) print("Num days", (d1 - d2).days)
def square(num): return num**2 def check_even(num): return num%2 == 0 def main(): print("== map ==") array = [1, 2, 3, 4] print("square", array, "->", [x for x in map(square, array)]) print("\n== filter ==") print("filter even", array, "->", [x for x in filter(check_even, array)]) print("\n== lambda expression ==") square_lambda = lambda num: num**2 print("square", array, "->", [x for x in map(square_lambda, array)]) # Naming the lambda is optional like it's done below print("square", array, "->", [x for x in map(lambda num: num**2, array)]) print("filter even", array, "->", [x for x in filter(lambda num: num%2 == 0, array)]) if __name__ == "__main__": main()
import random as rd def dice(): return rd.randint(1, 6) def main(): goal = int(input("目標点数は?")) mPoint = 0 ePoint = 0 while(True): # 自分のターン print("\nYour turn!") mini_sum = 0 input() while(True): print("ダイスを振りますか?") print("1:YES") print("2:NO") command = int(input()) if command == 1: d = dice() print(str(d) + "が出ました") if d == 1: print("アウトです") mini_sum = 0 break else: mini_sum += d print("只今" + str(mini_sum) + "point です") if command == 2: mPoint += mini_sum break print("Your point:" + str(mPoint)) print("Enemy point:" + str(ePoint)) if mPoint >= goal: print("You win!") break # 敵のターン print("\nEnemy turn!") mini_sum = 0 input() while(True): go = dice() if mini_sum == 0 or go != 1: d = dice() print(str(d) + "が出ました") if d == 1: print("アウトです") mini_sum = 0 break else: mini_sum += d print("只今" + str(mini_sum) + "point です") else: ePoint += mini_sum break input() print("Your point:" + str(mPoint)) print("Enemy point:" + str(ePoint)) if ePoint >= goal: print("Enemy win!") break if __name__ == "__main__": main()
from turtle import * from helpers import draw_circle from movement import no_delay import time import settings def draw_animation(num_frames,sleeptime): """Takes num_frames and sleeptime as arguments and draws the animation. Draws 3 circles on top of eachother. With each frame, the innermost and outermost circles rotate clockwise and the middle circle rotates anti-clockwise""" hideturtle() for i in range(num_frames): with no_delay(): clear() setheading(360-i) draw_circle(300) setheading(i) draw_circle(200) setheading(360-i) draw_circle(100) time.sleep(5) clear() def main(): for i in range(settings.NUMREPEATS): draw_animation(settings.NUMFRAMES, settings.SLEEPTIME) input("Press enter...") if __name__ == '__main__': screen = Screen() screen.setup(settings.SCREENWIDTH,settings.SCREENHEIGHT) main()
current_line =0 def print_a_line(line_count, f): print(line_count, f.readline()) current_file= open("test.txt") def printt(): print("Lets print three lines ") current_line = 0 current_line += 1 print_a_line(current_line, current_file) printt()
import random def escoge_numero(mochila): intentos = 0 num_max = 15 num_min = 1 print('¡Estas en la papelera, y te ha tocado el juego de ESCOGE UN NUMERO!') numero = random.randint(num_min, num_max) print('Debes decirme en que numero estoy pensando entre ' + str(num_min) + ' y ' + str(num_max)) while intentos < 3: adivina =input('Adivina el numero:') adivina = int(adivina) intentos += 1 if adivina < numero: print('Tu numero es muy bajo') elif adivina > numero: print('Tu numero es muy alto') elif adivina == numero: break if adivina == numero: print('Buen trabajo, ¡Adivinaste!, haz optenido el TITULO UNIVERSITARIO ') elif adivina != numero: numero = int(numero) print('No es correcto, perdiste un cuarto de vida, intentalo de nuevo, es numero era ' + str(numero)) #return #if intento > numero_vida: # print('LO SIENTO, TE QUEDASTE SIN VIDAS') # break
import random lista = [1,2,3] def pregunta1(mochila): #pregunta uno print(''' ¿En qué fecha es el Aniversario de la Universidad Metropolitana?", 1. 22 de octubre 2. 22 de septiembre 3. 25 de octubre 4. 25 de septiembre ''') respuesta_uno = input(''' - Coloca el numero de la respuesta correcta - Coloca 0 (CERO) para una pista ''') while respuesta_uno != '1' and respuesta_uno != '2' and respuesta_uno != '3' and respuesta_uno != '4' and respuesta_uno != '0': print(''' ¿En qué fecha es el Aniversario de la Universidad Metropolitana?", 1. 22 de octubre 2. 22 de septiembre 3. 25 de octubre 4. 25 de septiembre ''') respuesta_uno = input(''' - Coloca el numero de la respuesta correcta - Coloca 0 (CERO) para una pista ''') if respuesta_uno == '0': print('Es en octubre') print(''' ¿En qué fecha es el Aniversario de la Universidad Metropolitana?", 1. 22 de octubre 2. 22 de septiembre 3. 25 de octubre 4. 25 de septiembre ''') respuesta_uno = input(''' - Coloca el numero de la respuesta correcta ''') if respuesta_uno == '1': print('Respuesta correcta, te haz ganado el LIBRO DE MATEMATICA') else: print('Respuesta incorrecta, pierdes una vida') mochila['vidas'] -= 1/2 elif respuesta_uno == '1': print('Respuesta correcta, te haz ganado el LIBRO DE MATEMATICA') else: print('Respuesta incorrecta, pierdes una vida') mochila['vidas'] -= 1/2 print(f'Te quedan {mochila["vidas"]} vidas') def pregunta2(mochila): # pregunta dos print(''' ¿En qué año fue Fundada la Universidad Metropolitana?, 1. 1979 2. 1969 3. 1980 4. 1970 ''') respuesta_dos = input(''' - Coloca el numero de la respuesta correcta - Coloca 0 (CERO) para una pista ''') while respuesta_dos != '1' and respuesta_dos != '2' and respuesta_dos != '3' and respuesta_dos != '4' and respuesta_dos != '0': print(''' ¿En qué año fue Fundada la Universidad Metropolitana?, 1. 1979 2. 1969 3. 1980 4. 1970 ''') respuesta_dos = input(''' - Coloca el numero de la respuesta correcta - Coloca 0 (CERO) para una pista ''') if respuesta_dos == '0': print('Termina en 0 el año"') print(''' ¿En qué año fue Fundada la Universidad Metropolitana?, 1. 1979 2. 1969 3. 1980 4. 1970 ''') respuesta_dos = input(''' - Coloca el numero de la respuesta correcta ''') if respuesta_dos == '4': print('Respuesta correcta, te haz ganado el LIBRO DE MATEMATICA') else: print('Respuesta incorrecta, pierdes una vida') mochila['vidas'] -= 1/2 elif respuesta_dos == '4': print('Respuesta correcta, te haz ganado el LIBRO DE MATEMATICA') else: print('Respuesta incorrecta, pierdes una vida') mochila['vidas'] -= 1/2 print(f'Te quedan {mochila["vidas"]} vidas') def pregunta3(mochila): #pregunta tres print(''' ¿Quién fundó la Unimet? 1. Rafael Matiezo 2. Lorenzo Mendoza 3. Eugenio Mendoza 4. Luis Miguel Da Gama ''') respuesta_tres = input(''' - Coloca el numero de la respuesta correcta - Coloca 0 (CERO) para una pista ''') while respuesta_tres != '1' and respuesta_tres != '2' and respuesta_tres != '3' and respuesta_tres != '4' and respuesta_tres != '0': print(''' ¿Quién fundó la Unimet? 1. Rafael Matiezo 2. Lorenzo Mendoza 3. Eugenio Mendoza 4. Luis Miguel Da Gama ''') respuesta_tres = input(''' - Coloca el numero de la respuesta correcta - Coloca 0 (CERO) para una pista ''') if respuesta_tres == '0': print("Tiene una estatua") print(''' ¿Quién fundó la Unimet? 1. Rafael Matiezo 2. Lorenzo Mendoza 3. Eugenio Mendoza 4. Luis Miguel Da Gama ''') respuesta_tres = input(''' - Coloca el numero de la respuesta correcta ''') if respuesta_tres == '3': print('Respuesta correcta, te haz ganado el LIBRO DE MATEMATICA') else: print('Respuesta incorrecta, pierdes una vida') mochila['vidas'] -= 1/2 elif respuesta_tres == '3': print('Respuesta correcta, te haz ganado el LIBRO DE MATEMATICA') else: print('Respuesta incorrecta, pierdes una vida') mochila['vidas'] -= 1/2 print(f'Te quedan {mochila["vidas"]} vidas') def quizzi(mochila): print(''' ¡te encuentas en el Banco 1 Contesta estas preguntas en menos de un minutos para conseguir el libro de matematicas PRESIONA > PARA EMPEZAR ''') si = input() while si != '>': print(''' ¡Estas en la computadora 2! Debes de conseguir la contraseña, contestando estas adivinanzas ¿Estas listo? PRESIONA > PARA CONTINUAR ''') si = input() elegir = random.sample(lista,1) if elegir == 1: pregunta1(mochila) elif elegir == 2: pregunta2(mochila) else: pregunta3(mochila)
import tkinter from tkinter import ttk import crypto COINS = [ 'BTC', 'DOGE', 'XRP', 'ADA'] CURRENCIES = [ 'USD', 'EUR', 'HUF'] coin_choosed, currency_choosed = False, False def change_coin(value): global COIN global coin_choosed COIN = value coin_choosed = True # print(COIN, coin_choosed) return COIN, coin_choosed def change_curr(value): global CURRENCY global currency_choosed CURRENCY = value currency_choosed = True # print(CURRENCY, currency_choosed) return CURRENCY, currency_choosed def choose_coin(root): [child.destroy() for child in root.winfo_children()] root.grid() canvas = tkinter.Canvas(root) canvas.grid() for coin_opt in range(len(COINS)): btn = ttk.Button(canvas, text=COINS[coin_opt], command=None) btn.grid(row=coin_opt, column=0) btn['command'] = lambda btn=btn: [change_coin(btn['text']), crypto.main(root, COIN, CURRENCY) if currency_choosed and coin_choosed else None] for currency_opt in range(len(CURRENCIES)): btn = ttk.Button(canvas, text=CURRENCIES[currency_opt], command=None) btn.grid(row=currency_opt, column=1) btn['command'] = lambda btn=btn: [change_curr(btn['text']), crypto.main(root, COIN, CURRENCY) if currency_choosed and coin_choosed else None] #tkinter.Button(root, text='Plot!', command=lambda: crypto.main(root, COIN, CURRENCY)).grid() def main(root): global coin_choosed global currency_choosed coin_choosed, currency_choosed = False, False choose_coin(root) root.mainloop() if __name__ == '__main__': root = tkinter.Tk() main(root)
#!/usr/bin/python import argparse import sys from itertools import * import math import operator # calculate the number 1/m where m < n which has the longest repeating part of its fraction # technique: long division. Track remainder as dividing by n, populating a dict with # remainder -> decimal position; return [current] - [reposed] when we hit a loop. # ex. 1/6 -> 1: 10/6 = 1r4, rem[4] = 1; 2: 40/6 = 6r4 rem[4] is populated, loop = 2-1 = 1 # 1/7 -> 1: 10/7 = 1r3, rem[3] = 1; 2: 30/7 = 4r2, rem[2] = 2; 3: 20/7 = 2r6, rem[6] = 3; # 4: 60/7 = 8r4, rem[4] = 4; 5: 40/7 = 5r5, rem[5] = 5; 6: 50/7 = 7r1, rem[1] = 6; # 7: 10/7 = 1r3, rem[3] is populated w/1, loop = 7-1 = 6 def repeat_size(i): rems = {} num = 1 pos = 0 while True: rem = num * 10 % i if rem == 0: return 0 # terminating fraction if rem in rems: return pos - rems[rem] rems[rem] = pos num = rem pos += 1 def euler26(n): longest_len = 0 longest_val = None for i in range(2, n): rep_size = repeat_size(i) if rep_size > longest_len: longest_len = rep_size longest_val = i debug("{}: {}", longest_val, longest_len) return longest_val def debug_out(s, *args, **kwargs): print s.format(*args, **kwargs) def debug_noop(s, *args, **kwargs): pass debug = debug_noop class Usage(Exception): def __init__(self, msg): self.msg = msg def main(argv=None): if argv is None: argv = sys.argv try: try: parser = argparse.ArgumentParser(description='Euler problem ___.') parser.add_argument('--debug', action='store_true') parser.add_argument('--n', default=1000, type=long) args = parser.parse_args() except ArgumentError, msg: raise Usage(msg) global debug if args.debug: debug = debug_out total = euler26(args.n) print total except Usage, err: print >>sys.stderr, err.msg print >>sys.stderr, "for help use --help" return 2 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python import argparse import sys from itertools import * import math import operator # to start us off primes = [2, 3, 5, 7, 11, 13, 17, 19] primeSet = set(primes) def seedPrimes(upTo): for i in xrange(primes[-1]+2, upTo, 2): isPrime = True limit = int(math.sqrt(i)) for j in primes: if j > limit: break if i % j == 0: isPrime = False break if isPrime: primes.append(i) primeSet.add(i) def isPrime(n): if n in primeSet: return True for i in primes: if n % i == 0: return False primeSet.add(i) return True def rotations(n): s = str(n) for i in range(len(s)): yield int(s[i:] + s[:i]) def euler35(n): """A 'circular' prime is any number where all rotations of the digits are prime. Return all circular primes below n.""" seedPrimes(int(math.sqrt(n))) circCount = 0 for i in xrange(2, n): isCircPrime = True for ir in rotations(i): if not isPrime(ir): isCircPrime = False break if isCircPrime: circCount += 1 return circCount def debug_out(s, *args, **kwargs): print s.format(*args, **kwargs) def debug_noop(s, *args, **kwargs): pass debug = debug_noop class Usage(Exception): def __init__(self, msg): self.msg = msg def main(argv=None): if argv is None: argv = sys.argv try: try: parser = argparse.ArgumentParser(description='Euler problem 35.') parser.add_argument('--debug', action='store_true') parser.add_argument('--n', default=100, type=long) args = parser.parse_args() except ArgumentError, msg: raise Usage(msg) global debug if args.debug: debug = debug_out total = euler35(args.n) print total except Usage, err: print >>sys.stderr, err.msg print >>sys.stderr, "for help use --help" return 2 if __name__ == "__main__": sys.exit(main())
import unicodedata import re def unicode_to_ascii(s): """Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427""" return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' ) def normalize_string(s): """Lowercase, trim, and remove non-letter characters""" s = unicode_to_ascii(s) # ensure each math symbol is it's own token s = "".join([c if c.isalnum() else " {} ".format(c) for c in s]) # remove the unknowns since tools like wolfram are good at identifying them s = s[s.index(';') + 1:] # remove all extra whitespaces s = " ".join(s.split()) return s def remove_punctuation(s): """ Removes all punctuation tokens from text""" return re.subn(r"""[!.><:;',@#~{}\[\]\-_+=£$%^&()?]""", "", s, count=0, flags=0)[0] def generalize(text, equation): """ Replaces all numeric values with general variables """ word_var_mapping = dict() var_idx = 1 words = [] for s in text.split(' '): if s.isdigit(): var = f'var{var_idx}' words.append(var) word_var_mapping[s] = var var_idx += 1 else: words.append(s) general_text = ' '.join(words) words = [] for s in equation.split(' '): if s in word_var_mapping: words.append(word_var_mapping[s]) else: words.append(s) general_equation = ' '.join(words) return general_text, general_equation def text2int(textnum, numwords=None): """ Replaces all numbers that are written as words with their numeric representation """ if not numwords: numwords = {} units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] scales = ["hundred", "thousand", "million", "billion", "trillion"] numwords["and"] = (1, 0) for idx, word in enumerate(units): numwords[word] = (1, idx) for idx, word in enumerate(tens): numwords[word] = (1, idx * 10) for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0) ordinal_words = {'first': 1, 'second': 2, 'third': 3, 'fifth': 5, 'eighth': 8, 'ninth': 9, 'twelfth': 12} ordinal_endings = [('ieth', 'y'), ('th', '')] textnum = textnum.replace('-', ' ') current = result = 0 curstring = "" onnumber = False for word in textnum.split(): if word in ordinal_words: scale, increment = (1, ordinal_words[word]) current = current * scale + increment if scale > 100: result += current current = 0 onnumber = True else: for ending, replacement in ordinal_endings: if word.endswith(ending): word = "%s%s" % (word[:-len(ending)], replacement) if word not in numwords: if onnumber: curstring += repr(result + current) + " " curstring += word + " " result = current = 0 onnumber = False else: scale, increment = numwords[word] current = current * scale + increment if scale > 100: result += current current = 0 onnumber = True if onnumber: curstring += repr(result + current) return curstring
""" Kata: Sequence generator (6 kyu) Description: Write a generator sequence_gen ( sequenceGen in JavaScript) that, given the first terms of a sequence will generate a (potentially) infinite amount of terms, where each subsequent term is the sum of the previous x terms where x is the amount of initial arguments (examples of such sequences are the Fibonacci, Tribonacci and Lucas number sequences). Examples fib = sequence_gen(0, 1) fib.next() = 0 # first term (provided) fib.next() = 1 # second term (provided) fib.next() = 1 # third term (sum of first and second terms) fib.next() = 2 # fourth term (sum of second and third terms) fib.next() = 3 # fifth term (sum of third and fourth terms) fib.next() = 5 # sixth term (sum of fourth and fifth terms) fib.next() = 8 # seventh term (sum of fifth and sixth terms) trib = sequence_gen(0,1,1) trib.next() = 0 # first term (provided) trib.next() = 1 # second term (provided) trib.next() = 1 # third term (provided) trib.next() = 2 # fourth term (sum of first, second and third terms) trib.next() = 4 # fifth term (sum of second, third and fourth terms) trib.next() = 7 # sixth term (sum of third, fourth and fifth terms) lucas = sequence_gen(2,1) [lucas.next() for _ in range(10)] = [2, 1, 3, 4, 7, 11, 18, 29, 47, 76] Note: You can assume you will get at least one argument and any arguments given will be valid (positive or negative integers) so no error checking is needed. Note for Ruby users: sequence_gen should return an Enumerator object. Any feedback/suggestions would much appreciated. URL: https://www.codewars.com/kata/sequence-generator """ from collections import deque def sequence_gen(*args): a = deque(args) for i in a: yield i while True: s = sum(a) yield s a.popleft() a.append(s)
""" Kata: Validate Sudoku with size `NxN` (4 kyu) Description: Given a Sudoku data structure with size NxN, N > 0 and √N == integer, write a method to validate if it has been filled out correctly. The data structure is a multi-dimensional Array, ie: [ [7,8,4, 1,5,9, 3,2,6], [5,3,9, 6,7,2, 8,4,1], [6,1,2, 4,3,8, 7,5,9], [9,2,8, 7,1,5, 4,6,3], [3,5,7, 8,4,6, 1,9,2], [4,6,1, 9,2,3, 5,8,7], [8,7,6, 3,9,4, 2,1,5], [2,4,3, 5,6,1, 9,7,8], [1,9,5, 2,8,7, 6,3,4] ] Rules for validation Data structure dimension: NxN where N > 0 and √N == integer Rows may only contain integers: 1..N (N included) Columns may only contain integers: 1..N (N included) 'Little squares' (3x3 in example above) may also only contain integers: 1..N (N included) URL: https://www.codewars.com/kata/validate-sudoku-with-size-nxn """ from math import sqrt class Sudoku(object): def __init__(self, board): self.board = board self.n = len(self.board) self.sqrtn = int(sqrt(self.n)) def is_valid(self): # Check size and contents for row in self.board: if len(row) != self.n: return False for n in row: # Make sure every entry is an integer and is in range if not type(n) is int or not self.in_range(n): return False # Check rows and columns for n in xrange(self.n): if not self.valid_row(n) or not self.valid_col(n): return False # Check squares for i in xrange(self.sqrtn): for j in xrange(self.sqrtn): if not self.valid_square(i,j): return False return True def in_range(self, n): return n >= 1 and n <= self.n def valid_row(self, i): valid = [False]*self.n row = self.board[i] for n in row: try: valid[n-1] = True except IndexError: return False return all(valid) def valid_col(self, j): valid = [False]*self.n col = [row[j] for row in self.board] for n in col: try: valid[(n-1)] = True except IndexError: return False return all(valid) def valid_square(self, ni, nj): ni *= self.sqrtn nj *= self.sqrtn valid = [False]*self.n for i in xrange(ni, ni+self.sqrtn): for j in xrange(nj, nj+self.sqrtn): n = self.board[i][j] try: valid[n-1] = True except IndexError: return False return all(valid)
""" Kata: Tax Calculator (7 kyu) Description: Write a function to calculate compound tax using the following table: For $10 and under, the tax rate should be 10%. For $20 and under, the tax rate on the first $10 is %10, and the tax on the rest is 7%. For $30 and under, the tax rate on the first $10 is still %10, the rate for the next $10 is still 7%, and everything else is 5%. Tack on an additional 3% for the portion of the total above $30. Return 0 for invalid input(anything that's not a positive real number). Examples: An input of 10, should return 1 (1 is 10% of 10) An input of 21, should return 1.75 (10% of 10 + 7% of 10 + 5% of 1) * Note that the returned value should be rounded to the nearest penny. URL: https://www.codewars.com/kata/tax-calculator """ def tax_calculator(total): # Return zero for invalid instances if not (isinstance(total, int) or isinstance(total, float)) or total <= 0: return 0 # $10 or less if total <= 10: return round(0.1*total,2) # $20 or less elif total <= 20: return round(1 + 0.07*(total-10), 2) # $30 or less elif total <= 30: return round(1.7 + 0.05*(total-20), 2) # More than $30 else: return round(2.2 + 0.03*(total-30), 2)
""" Kata: IPv4 Parser (6 kyu) Description: Problem Statement Write a function that takes two string parameters, an IP (v4) address and a subnet mask, and returns two strings: the network block, and the host identifier. The function does not need to support CIDR notation. Description A single IP address with subnet mask actually specifies several addresses: a network block, and a host identifier, and a broadcast address. These addresses can be calculated using a bitwise AND operation on each bit. (The broadcast address is not used in this kata.) Example A computer on a simple home network might have the following IP and subnet mask: IP: 192.168.2.1 Subnet: 255.255.255.0 (CIDR Notation: 192.168.2.1 /24) In this example, the network block is: 192.168.2.0. And the host identifier is: 0.0.0.1. bitwise AND To calculate the network block and host identifier the bits in each octet are ANDed together. When the result of the AND operation is '1', the bit specifies a network address (instead of a host address). To compare the first octet in our example above, convert both the numbers to binary and perform an AND operation on each bit: 11000000 (192 in binary) 11111111 (255 in binary) --------------------------- (AND each bit) 11000000 (192 in binary) So in the first octet, '192' is part of the network address. The host identifier is simply '0'. For more information see the Subnetwork article on Wikipedia. URL: https://www.codewars.com/kata/ipv4-parser """ # Write a function that takes two string parameters, an IP (v4) address and # a subnet mask, and returns two strings: the network block, # and the host identifier. # For example: # >>> print ipv4__parser('192.168.50.1', '255.255.255.0') # ('192.168.50.0', '0.0.0.1') def ipv4__parser(ip_addr, mask): ip_list = ip_addr.split('.') mask_list = mask.split('.') net_list = [] host_list = [] for i in xrange(4): net_list.append(str(int(ip_list[i]) & int(mask_list[i]))) host_list.append(str(int(ip_list[i]) & ~int(mask_list[i]))) net_addr = '.'.join(net_list) host_addr = '.'.join(host_list) return net_addr, host_addr
""" Kata: Dbftbs Djqifs ("Caeser Cipher" with 1 letter shift) (6 kyu) Description: Caesar Ciphers are one of the most basic forms of encryption. It consists of a message and a key, and it shifts the letters of the message for the value of the key. Your task is to create a function encryptor that takes 2 arguments - key and message - and returns the encrypted message. A message 'Caesar Cipher' and a key of 1 returns 'Dbftbs Djqifs'. A message 'Caesar Cipher' and a key of -1 returns 'Bzdrzq Bhogdq'. Make sure to only shift letters, and be sure to keep the cases of the letters the same. All punctuation, numbers, spaces, and so on should remain the same. Also be aware of keys greater than 26 and less than -26. There's only 26 letters in the alphabet! URL: https://www.codewars.com/kata/dbftbs-djqifs """ def encryptor(key, message): if key < -26: while key < -26: key += 26 elif key > 26: while key > 26: key -= 26 new_msg = '' for char in message: if not char.isalpha(): new_msg += char elif char.isupper(): new_msg += char_shift(key, char, 65, 90) elif char.islower(): new_msg += char_shift(key, char, 97, 122) return new_msg def char_shift(key, char, lo, hi): new_let = ord(char) + key if new_let > hi: new_let = lo + (new_let - hi) - 1 elif new_let < lo: new_let = hi - (lo - new_let) + 1 return chr(new_let)
# Sys is used to exit the program in case the libraries needed are not isntalled import sys try: import cv2 except: print("You need to install Opencv \n Run this command \n pip install python-opencv") sys.exit(1) #Numpy will be installed along Open-cv automatically import numpy as np try: # We use matplotlib to display and image from matplotlib import pyplot as plt except: print("You need to install matplotlib \n Run this command \n pip install matplotlib") sys.exit(1) # Loading cat.jpg or replace it with another custom image img = cv2.imread('cat.jpg') #img = cv2.imread('cat.jpg',0) #This converts the image to grayscale print ('\nimg is in the form of:',type(img)) print ('\nimg shape is:') print (img.shape) # Converting BGR to RGB because cv2 works in BGR # While matplotlib works in RGB img =cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(img) plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show()
# given a number, print it's factors # get user input for number and set a variable for factor numbers inp = int(input("Give me a number, any number: ")) num_of_factor = 1 # Logic while num_of_factor <= inp: if inp % num_of_factor == 0: # if input can be divided evenly by number, it is a factor print(num_of_factor) num_of_factor += 1 # increment factor by 1 continue # start loop again else: # if input cannot be divided evenly by number, it is not a factor so we do not print num_of_factor += 1 # increment factor by 1 continue # start loop again
import unittest from simplex import Simplex class MyTestCase(unittest.TestCase): def test_something(self): s = Simplex() funcao_objetivo = [-2, -1, 1] restricoes = [["<=", 1, 1, 2, 6], ["<=", 1, 4, -1, 4], [0, ">=", ">=", ">="]] #Passo 0 s.forma_padrao(funcao_objetivo, restricoes) print("Solução Básica Inicial") print(s.solve) while not (s.is_otima()): variavelEntra = s.quem_entra() print("Variável que entra") print(variavelEntra) variavelSai = s.quem_sai(variavelEntra) print("Variável que sai") print(variavelSai) s.new_solution(sai=variavelSai, entra=variavelEntra) print("Novo Tableau") print(s.tableau) self.assertEqual((-1)*s.tableau[s.quantRest][s.quantVar-1], -26/3) if __name__ == '__main__': unittest.main()
import sys from chessBoard import * class Agent: def __init__(self, turn, colour): self.turn=turn #A flag that is true when its Computer's turn self.colour=colour self.attacked=0 self.attackedPieces=[] self.score=0 def game(user, chessBot): board=chessBoard() board.initializeBoard() board.displayChessBoard() playing=True while playing: print("\033[1;32;40m Enter current position and destined position\n") currentpos=input() destpos=input() if board.moveChessPiece(currentpos,destpos, user): # PLAYER MOVE playing=board.checkWinning(user, chessBot) #board.randomMoveChessPiece(chessBot,user) #bestMove=Move(0,0,0,0) val,bestMove=board.minmax(chessBot, user, True, 3) board.noOfMovesHistory += 1 print(bestMove.startX, bestMove.startY, bestMove.endX, bestMove.endY) startIdentifier = chr(ord('a') + bestMove.startY) + str(8 - bestMove.startX) endIdentifier = chr(ord('a') + bestMove.endY) + str(8 - bestMove.endX) board.moveChessPiece(startIdentifier,endIdentifier, chessBot) # BOT MOVE print(startIdentifier, endIdentifier) board.displayChessBoard() board.noOfMovesHistory += 1 playing=board.checkWinning(user, chessBot) # check winning after each move board.updateGamePhase() else: print("!!! Invalid Move !!!") board.checkPawnPromotion() user=Agent(True, "white") #We will have two agents, user and chess bot chessBot=Agent(False, "black") game(user, chessBot) #1. prompt user to enter his move (store moves as well) #2. update chessboard #3. Agent's turn (decide which move is the best using minmax and alpha puning) #4. update chessboard #5. display it #6. repeat
#!/bin/env python """ Write a function with the following signature: title(str) -> str It should take a string and capitalize it according to book title rules eg: title("a tale of two cities") => A Tale of Two Cities """ lowercase = ["a", "of", "an", "the", "to", "at", "in", "with", "and", "for", "but", "or", "from"] def title(my_title): words = my_title.split() title = "" for i in range(len(words)): if words[i] not in lowercase or i == 0: cap_word = words[i][0].upper() if len(words[i]) > 1: cap_word += words[i][1:] if i != 0: title += " " title += cap_word else: title += " " + words[i] return title print title("cat in the hat with a bat")
from abc import ABCMeta, abstractclassmethod import sys class Zoo(object): animals = {} def __init__(self, name): # 动物园名字 self.name = name @classmethod def add_animal(cls, animal): if animal not in cls.animals: cls.animals[animal] = animal if not hasattr(cls, animal.__class__.__name__): setattr(cls, animal.__class__.__name__, animal) class Animal(metaclass=ABCMeta): @abstractclassmethod def __init__(self, genre, physique, character): self.genre = genre self.physique = physique self.character = character @property def is_fierce_creatures(self): return (self.physique == '中型' or self.physique == '大型') and self.genre == '食肉' and self.character == '凶猛' @property def as_pets(self): return (self.physique != '凶猛') class Cat(Animal): sound = '喵' def __init__(self, name,genre,physique,character): # 动物名字 self.name = name super().__init__(genre, physique, character) class Dog(Animal): sound = 'WoWo' def __init__(self, name,genre,physique,character): # 动物名字 self.name = name super().__init__(genre, physique, character) if __name__ == '__main__': # 实例化动物园 z = Zoo('时间动物园') # 实例化一只猫,属性包括名字、类型、体型、性格 cat1 = Cat('大花猫 1', '食肉', '小', '温顺') # 增加一只猫到动物园 z.add_animal(cat1) # 动物园是否有猫这种动物 have_cat = hasattr(z, 'Dog') print(have_cat)
import math import sys #Functions def calculateSideLength(sides, radius): degrees = math.radians(180) #convert from degrees to radians sideLength = (math.tan(degrees/sides) * 2) / radius #Calculate the side length of a polygon based on num sides and the radius of said polygon return sideLength def calculatePerimiter(sides, radius): sideLength = calculateSideLength(sides, radius) perimiter = sideLength * sides return perimiter def calculatePi(sides, radius): perimiter = calculatePerimiter(sides, radius) piApproximation = perimiter/(radius * 2) return piApproximation # Logic radius = 1; if len(sys.argv) > 1: sides = int(sys.argv[1]) # Square else: sides = 1000 # while(sides <= 10000): # piApprox = calculatePi(sides, radius) # sides += 100000 # print("Sides: " + str(sides) + " pi: " + '{0:.50f}'.format(piApprox)) piApprox = calculatePi(sides, radius) print("Sides: " + str(sides)) print("Pi Approx : " + '{0:.50f}'.format(piApprox)) print("Pi Constant: " + '{0:.50f}'.format(math.pi))
# fibonacci sequence 0,1,1,2,3,5,8,13,21 # write function which takes number and print this number of item of fibonacci sequence def fib(n): i = 1 fibonacci = [0,1] while i < n: fibN = fibonacci [i-1] + fibonacci [i] fibonacci.append (fibN) i += 1 print (fibonacci) #fib(10) def fib2(n): a, b, cnt = 0, 1, 2 if n > 0: print (a) if n > 1: print (b) while cnt < n: a, b = b, a+b cnt += 1 print(b) #fib(2) def fib3 (n): i = 0 fibN = 0 fibonacci = [0,1] while fibonacci [i] + fibonacci [i+1] < n: fibN = fibonacci [i] + fibonacci [i+1] fibonacci.append (fibN) i += 1 print (fibonacci) fib3 (10)
# task 1 - function takes two coordinates of two rooks on a chessboard, returns true or false if the rooks can take each other # we supposse that chessboard has size 8 x 8 (coordinates cannot be grater than 8) # we supposse that the two coordinates are different from each other def rooks(l1, l2): if l1[0] == l2[0] or l1[1] == l2[1]: return True else: return False # exaple of function call # first coordinate is column, second id row #print (rooks([2,4], [5,6])) # task 2 - do the same with queens def queens(l1, l2): if rooks(l1, l2): return True if l1[0] - l2[0] == l1[1] - l2[1]: return True if l1[0] - l2[0] == l2[1] - l1[1]: return True return False # task 3 - test function queens #print (queens([2,4],[5,6])) #print (queens([2,4],[2,8])) #print (queens([2,1],[8,7])) #print (queens([1,8],[8,1])) #print (queens([1,7],[7,1])) # task 4 - write function kings def kings (l1,l2): if (l1[0] == l2[0] or l1[0] == l2[0]+1 or l1[0] == l2[0]-1) and (l1[1] == l2[1] or l1[1] == l2[1]+1 or l1[1] == l2[1]-1): return True else: return False def kings2(l1,l2): return abs(l1[0] - l2[0]) <= 1 and abs(l1[1] - l2[1]) <= 1 #print (kings ([3,3],[3,8])) # task 5 - write function knights (jezdec / kun) def knights (l1,l2): if l1[0] == l2[0]-2 and l1[1] == l2[1]+1: return True if l1[0] == l2[0]-1 and l1[1] == l2[1]+2: return True if l1[0] == l2[0]-2 and l1[1] == l2[1]-1: return True if l1[0] == l2[0]-1 and l1[1] == l2[1]-2: return True if l1[0] == l2[0]+2 and l1[1] == l2[1]+1: return True if l1[0] == l2[0]+1 and l1[1] == l2[1]+2: return True if l1[0] == l2[0]+2 and l1[1] == l2[1]-1: return True if l1[0] == l2[0]+1 and l1[1] == l2[1]-2: return True else: return False def knights2(l1, l2): return abs(l1[0] - l2[0]) + abs(l1[1] - l2[1]) == 3 and not rooks(l1,l2) #print (knights ([3,3],[3,8])) #print (knights ([3,3],[2,5]))
def sortList(lst): isListSorted = False while not isListSorted: i = 0 isListSorted = True while i < len (lst) - 1: if lst[i] > lst[i + 1]: lst[i], lst[i+1] = lst[i+1], lst[i] isListSorted = False i = i + 1 return lst # test 1 unsortedLst = [3,4,6,6,3,5] sortedLst = [3,3,4,5,6,6] result = sortList(unsortedLst) #expected = [3,3,4,5,6,6] #actual = sortList(... if result == sortedLst: print("test 1 ok") else: print("test 1 failed, expected", sortedLst, " but i got ", result) # test 2 unsortedLst = [] sortedLst = [] result = sortList(unsortedLst) if result == sortedLst: print("test 2 ok") else: print("test 2 failed, expected", sortedLst, " but i got ", result) # test 3 unsortedLst = [1] sortedLst = [1] result = sortList(unsortedLst) if result == sortedLst: print("test 3 ok") else: print("test 3 failed, expected", sortedLst, " but i got ", result) # test 4 unsortedLst = [3,3,3,3,3,3] sortedLst = [3,3,3,3,3,3] result = sortList(unsortedLst) if result == sortedLst: print("test 4 ok") else: print("test 4 failed, expected", sortedLst, " but i got ", result)
# IPND Stage 2 Final Project # For this project, we shall be building a Fill-in-the-Blanks quiz. # Our quiz will prompt a user with a paragraph containing several blanks. # The user should then be asked to fill in each blank appropriately to complete the paragraph. # This can be used as a study tool to help us remember important vocabulary! blanks = ["___1___", "___2___", "___3___", "___4___"] easy_quiz = '''___1___ in physics, is the rate of change of velocity of an object with respect to time. ___2___ is any interaction that, when unopposed, will change the motion of an object. ___3___ of a distribution of mass in space is the unique point where the weighted relative position of the distributed mass sums to zero, or the point where if a force is applied it moves in the direction of the force without rotating. ___4___ is the measure of an object's resistance to acceleration (a change in its state of motion) when a net force is applied. Source: Wikipedia and Tutorialspoint''' medium_quiz = '''___1___ is the rotational analog of linear momentum. ___2___ of a body is the rate of change of its angular displacement with respect to time. ___3___ is a movement of an object along the circumference of a circle or rotation along a circular path. ___4___ is an inertial force (also called a "fictitious" or "pseudo" force) directed away from the axis of rotation that appears to act on all objects when viewed in a rotating frame of reference. Source: Wikipedia''' hard_quiz = '''___1___ relates the integrated magnetic field around a closed loop to the electric current passing through the loop. ___2___ is a law of physics that describes force interacting between static electrically charged particles. ___3___ is a basic law of electromagnetism predicting how a magnetic field will interact with an electric circuit to produce an electromotive force (EMF)—a phenomenon called electromagnetic induction. ___4___ indicates that the induced EMF and the change in magnetic flux have opposite signs. is Source: Wikipedia''' easy_answers = ["Acceleration", "Force", "Center of mass", "Mass"] medium_answers = ["Angular Momentum", "Angular Velocity", "Circular Motion", "Centrifugal Force"] hard_answers = ["Ampere's circuital law", "Coulomb's law", "Faraday's law of induction", "Lenz's law"] def get_name(): """ Behavior: This method is get_name method. All names of the users are generated by this method :param level: None :return: Name """ name = raw_input("Please enter your name: ") if (name == ""): print "Name can't be empty.\n" get_name() else: print "Hello " + name + ", " return name def get_level(): """ Behavior: This method is get_level method. All levels of the games are generated by this method :param level: None :return: Level """ level = raw_input( "Please select a difficulty level for your quiz" "(easy, medium, or hard):") if level.lower() in ["easy", "medium", "hard"]: print "You chose " + level.lower() + "\n" return level.lower() else: print "You entered an invalid difficulty level.\n" get_level() def word_in_pos(word, parts_of_speech): """ Behavior: This method is words_in_pos method, which is used to identify whether a substring of word is in the parts_of_speech list. :param level: word,parts_of_speech :return: pos or None """ for pos in parts_of_speech: if pos in word: return pos return None def fill_in(quiz, blank, answer): """ Behavior: This method is wfill_in method, which is for users to add answers to the blank spaces. :param level: quiz, blank, answer :return: replaced """ quiz = quiz.split() replaced = [] for word in quiz: if (word == blank): word = word.replace(blank, answer) replaced.append(word) else: replaced.append(word) replaced = " ".join(replaced) return replaced def quiz_check(quiz, answers): """ Behavior: This method is quiz_check method, which is used to check if the answers the users input are correct. :param level: quiz, answers :return: None(only print things) """ index = 0 for blank in blanks: player_answers = raw_input( "\nPlease fill in blank # " + str(index+1) + ": ") while player_answers.lower() != answers[index].lower(): print "\nNah. Bruh, your answer was wrong. Please try again." player_answers = raw_input("Type it here again: ") print "\nAwesome, that's my homie!\n" quiz = quiz.replace(blank, answers[index]) print "QUIZ\n" + quiz index += 1 def setup_quiz(level): """ Behavior: This method is setup_quiz method, which is used to set the difficulty of the quiz. :param level: level :return: different quizzes and corresponding answers. """ if(level == "easy"): print "QUIZ\n" + easy_quiz return easy_quiz, easy_answers elif(level == "medium"): print "QUIZ\n" + medium_quiz return medium_quiz, medium_answers else: print "QUIZ\n" + hard_quiz return hard_quiz, hard_answers def play_quiz(): """ Behavior: This method is play_quiz method, which is used to create a general quiz structure by connecting previous functions together. :param level: None :return: None(only prints messages when the quiz has been finished) """ name = get_name() level = get_level() quiz, answers = setup_quiz(level) quiz_check(quiz, answers) print "\nCongrats, " + name + ", You've finished the quiz!\n" play_quiz()
class Rational : def __init__(self,numerateur,denominateur): self.__numerateur=numerateur self.__denominateur=denominateur def __euclide(self,a,b): while a != b : if a>b : a-=b else : b-=a return a def __add__(self,other): if isinstance(other,Rational) : return Rational(self.__numerateur*other.__denominateur+self.__denominateur*other.__numerateur,self.__denominateur*other.__denominateur) def __sub__(self,other): if isinstance(other,Rational) : return Rational(self.__numerateur*other.__denominateur-self.__denominateur*other.__numerateur,self.__denominateur*other.__denominateur) def __mul__(self,other): if isinstance(other,Rational) : return Rational(self.__numerateur*other.__numerateur,self.__denominateur*other.__denominateur) def __truediv__(self, other): if isinstance(other,Rational) : return Rational(self.__numerateur*other.__denominateur,self.__denominateur*other.__numerateur) def __str__(self): return str(self.__numerateur)+'/'+str(self.__denominateur) def __eq__(self,other): a=self.__euclide(other.__numerateur,other.__denominateur) New_other=Rational(other.__numerateur/a,other.__denominateur/a) a=self.__euclide(self.__numerateur,self.__denominateur) New_self=Rational(self.__numerateur/a,self.__denominateur/a) return New_other.__numerateur == New_self.__numerateur and New_other.__denominateur == New_self.__denominateur def __ne__(self,other): a=self.__euclide(other.__numerateur,other.__denominateur) New_other=Rational(other.__numerateur/a,other.__denominateur/a) a=self.__euclide(self.__numerateur,self.__denominateur) New_self=Rational(self.__numerateur/a,self.__denominateur/a) return New_other.__numerateur != New_self.__numerateur or New_other.__denominateur != New_self.__denominateur def __lt__(self,other): if isinstance(other,Rational) : return other.__numerateur/other.__denominateur > self.__numerateur/self.__denominateur def __gt__(self,other): if isinstance(other,Rational) : return other.__numerateur/other.__denominateur < self.__numerateur/self.__denominateur if __name__ == '__main__' : a=Rational(1,2) b=Rational(2,4) c=a+b d=a-b e=a*b f=a/b print(c,d,e,f) print(a==b,a!=b) print(c,a,c>a,c<a)
import tkinter as tk window = tk.Tk() greeting = tk.Label(text="Hello, Tkinter",background="blue",foreground="yellow") greeting.pack() button = tk.Button( text="Click me!", width=5, height=5, bg="blue", fg="yellow", ) button.pack() entry = tk.Entry(fg="yellow", bg="blue", width=50) entry.pack() window.mainloop()
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): copy = matrix.copy() i = 0 while i < len(matrix): copy[i] = list(map(lambda x: x ** 2, matrix[i])) i += 1 return copy
#!/usr/bin/python3 """ Module: Pascal's Triangle """ def pascal_triangle(n): """ function that returns a list of lists of integers representing the Pascal’s triangle of n """ list = [] if n <= 0: return [] list =[[1]] for i in range(0, n-1): temporal = [0] + license[1] +[0] sub_list = [] for j in range(len(temporal) - 1): sub_list.append(temporal[j] + temporal[j + 1]) list.append(sub_list) return list
#!/usr/bin/python3 """Module: Reads a text file (UTF8) and prints it to stdout""" def read_file(filename=""): """ function that reads a text file (UTF8) and prints it to stdout """ with open(filename, 'r', encoding='utf-8') as new_file: print(new_file.read(), end='')
#!/usr/bin/python3 """ Module: script that adds all arguments to a Python list, and then save them to a file""" from sys import argv save_to_json_file = __import__('5-save_to_json_file').save_to_json_file load_from_json_file = __import__('6-load_from_json_file').load_from_json_file try: new_list = load_from_json_file('add_item.json') except: new_list = [] for i in range(1, len(argv)): new_list.append(argv[i]) save_to_json_file(new_list, 'add_item.json')
import math def solution_1_divide_by_10(number): """ Divide the number by 10 till it becomes zero. Number of iteration is the result. """ count = 0 while number > 0: number = int(number / 10) count = count + 1 return count def solution_2_recursive(number): if number == 0: return 0 number = int(number / 10) return 1 + solution_2_recursive(number) def solution_3_log_base_10(number): return int(math.log10(number)) + 1 print(f'solution 1 result - {solution_1_divide_by_10(12345)}') print(f'solution 2 result - {solution_2_recursive(12345)}') print(f'solution 3 result - {solution_3_log_base_10(12345)}')
# Based on Andre Torres' tutorial here: # https://www.pythoncentral.io/finding-duplicate-files-with-python/ import os import sys import hashlib def findDup(parentFolder): # Dups in format {hash:[names]} dups = {} for dirName, subdirs, fileList in os.walk(parentFolder): print('Scanning %s...' % dirName) counter = 0 for filename in fileList: counter += 1 sys.stdout.write('\rfiles scanned: {}'.format(counter)) sys.stdout.flush() # Get the path to the file path = os.path.join(dirName, filename) # Calculate hash file_hash = hashfile(path) # Add or append the file path if file_hash in dups: dups[file_hash].append(path) else: dups[file_hash] = [path] return dups # Join two dictionaries def joinDicts(dict1, dict2): for key in dict2.keys(): if key in dict1: dict1[key] = dict1[key] + dict2[key] else: dict1[key] = dict2[key] def hashfile(path, blocksize = 65536): afile = open(path, 'rb') hasher = hashlib.md5() buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) afile.close() return hasher.hexdigest() def printResults(dict1): results = list(filter(lambda x: len(x) > 1, dict1.values())) if len(results) > 0: print('\n\n{} duplicates found:'.format(len(results))) print('The following files are identical. The name could differ, but the content is identical') print('___________________') for result in results: for subresult in result: print('\t%s' % subresult) print('___________________') else: print('No duplicate files found.') if __name__ == '__main__': if len(sys.argv) > 1: dups = {} folders = sys.argv[1:] for i in folders: # Iterate the folders given if os.path.exists(i): # Find the duplicated files and append them to the dups joinDicts(dups, findDup(i)) else: print('{} is not a valid path, please verify'.format(i)) sys.exit() printResults(dups) else: print( 'Usage:\t\tOption #1. python {} folder\n'\ .format(os.path.basename(__file__)) + '\t\tOption #2. python {} folder1 folder2 folder3'\ .format(os.path.basename(__file__)) )
#!/usr/bin/env python3 import itertools import editdistance def read_input(): with open('./input.txt', 'r') as input: for line in input: yield line def get_unique_occurrences(input): occurrences = [ (g[0], len(list(g[1]))) for g in itertools.groupby(sorted(input)) ] twos = [twos for twos in occurrences if twos[1] == 2] threes = [threes for threes in occurrences if threes[1] == 3] return ( True if len(twos) > 0 else False, True if len(threes) > 0 else False ) def get_edit_distance(left, right): return editdistance.eval(left, right) def main(): twos, threes = 0, 0 common_ids = None lines = [] for line in read_input(): _two, _three = get_unique_occurrences(line) twos += _two threes += _three lines.append(line) for line in lines: for match in lines: if line == match: continue else: distance = get_edit_distance(line, match) if distance == 1: common_ids = [line, match] break checksum = twos * threes print( 'Checksum: {} * {} = {}'.format( twos, threes, checksum ) ) print('Lev=1:\n\t{}\n\t{}'.format(common_ids[0], common_ids[1])) print( 'Common elements:\t{}'.format( ''.join([ elem for idx, elem in enumerate(common_ids[0]) if elem == common_ids[1][idx] ]) ) ) if __name__ == '__main__': main()
import os def parse_input() -> list[list[int]]: parsed_input: list[list[int]] = [] with open( os.path.dirname(os.path.abspath(__file__)) + '/input.txt', 'r', encoding='utf-8') as f: _tmp: list[int] = [] for line in f: _line = line.strip() if _line: _tmp.append(int(_line)) else: parsed_input.append(_tmp) _tmp = [] return parsed_input def collect_calories(elves: list[list[int]]) -> list[int]: elf_calories: list[int] = [] for elf in elves: elf_calories.append(sum(elf)) return elf_calories def main(): elf_loads = parse_input() elf_calories = sorted(collect_calories(elf_loads), reverse=True) print(f'The elf carrying the most has {elf_calories[0]} calories') print(f'The top 3 elves together are carrying {sum(elf_calories[0:3])}') if __name__ == '__main__': main()
#-*- coding = utf-8 -*- #@Time : 2020/4/15 21:47 #@Author : Shanhe.Tan #@File : hello.py #@Software : PyCharm #my first python program print("hello world") #comment ''' comment a = 10 print("This is :", a) ''' ''' #format output age = 18 print("My age is %d \r\n" %age) age += 1 print("My age is %d \r\n" %age) age += 1 print("My age is %d \r\n" %age) print("www","baidu","com", sep=".") ''' ''' password = input("password:") print("The password is ",password) print(type(password)) print("the number is %s" %password) ''' a = int("123") print(type(a)) b = a + 100 print(b) c = int(input("input:")) print("input number: %d" %c)
# -*- coding: utf-8 -*- __author__ = 'Илья' from threading import Thread, Lock #import time, threading lock = Lock() def method(): lock.acquire() # time.sleep(5) text = "Привет Мир\n" f = open("my.txt", "a") f.write(text) lock.release() def method2(): lock.acquire() # time.sleep(5) text = "Это Вася\n" f = open("my.txt", "a") f.write(text) lock.release() def method3(): lock.acquire() # time.sleep(5) text = "Всем пока\n" f = open("my.txt", "a") f.write(text) lock.release() if __name__ == '__main__': th = Thread(target=method, args=()) #th.setDaemon(True) сделать поток независимым от родителя th.start() th.join() th2 = Thread(target=method2, args=()) th2.start() th2.join() th3 = Thread(target=method3, args=()) th3.start() th3.join()
n = int(input("enter the numbers :")) c = [] d = 1 for i in range (n): i = int(input(" ")) c.append(i) d = d*i print(d)
x = 0 while True: x = int(input("Введи число в десятичной системе счисления: ")) base = int(input('Введи основание системы счисления в десятичной системе счисления: ')) number_string = "" # обрамления каждого разряда скобочками для систем счисления с основанием, большим 10 br1 = "(" * (base > 10) br2 = ")" * (base > 10) while x > 0: number_string = br1 + str(x % base) + br2 + number_string x = x // base print(number_string)
from random import random def main(): """ Grasshoper jumps from point 1 to point n from in one direction. |-|---|-|-...-| 0-1-2-x-4-5-...-n Available jumps: 1 interval, 2 intervals, 3 intervals between points. Point i=0 is not available for visiting. Some points are not available for jumps (ap[i] == False) Each point have cost of visiting c[i]. Program: - returns maximum number of allowed trajectories at each point of grasshopper path (p:list). - returns minimum cost of going from start to each other (s:list) where c[i] is cost of visiting point p[i]. """ n = 10 # >= 3 necessarily p = [0, 1, 1, 2] + [0] * (n - 3) # generate list for n points ap = [False] + [True] * n # availability of points - all are av beside 0 ap[4] = ap[7] = ap[9] = False # some unavailable points c = [int(random() * 5) + 1 if ap[i] else 0 for i in range(n+1)] # cost of visiting point ct = [0, c[1], c[2] + c[1], c[1] + c[3]] + [0] * (n - 3) # cost total from 1 to i for i in range(4, n + 1): if ap[i]: p[i] = p[i - 1] + p[i - 2] + p[i - 3] # Total cost of path from p[1] to p[i] consist of cost of p[i] and min cost of tree left point: # ct[i] = c[i] + min( c[i-1], c[i-2], c[i-3] ) ct[i] = min(ct[i - j] for j in range(1, 4) if ap[i-j]) + c[i] # print(*list(map(lambda x: " " + str(x) + " " if x != 0 else "00", p))) print("Indexes of points :", [i for i in range(n + 1)]) print("Availability of points :", list(map(int, ap))) print("Num of trajectories :", p) print() print("Cost of visiting each point:", c) print("Min cost to come to point :", ct) return main()