text
stringlengths
37
1.41M
def get_new_path (path, where): if not where: return path if where[0] == '.': where = where[1:] if not where: return path where = where[1:] return get_new_path (path, where) if where[0] == '..': where = where [1:] if not path: return path path.pop() path.pop() if not where: return path where = where[1:] return get_new_path (path, where) if not where[0].isalnum(): return where[0] + ": No such file or directory" if path [-1] != '/': path.append ('/') path.append (where[0]) where = where[1:] if not where: return path where = where[1:] return get_new_path (path, where) while True: print ("# ", end = "") command = input().split() if len(command) != 3: print ("Bad input") continue if command[0] != 'mycd': print ("Bad input") continue path = command[1] where = command[2] while path.find("//") != -1: path = path.replace ("//", "/") print (path) while where.find("//") != -1: where = where.replace ("//", "/") path = path.replace ("/", "@/@").split("@") path = [item for item in path if item != ''] where = where.replace ("/", "@/@").split("@") where = [item for item in where if item != ''] if where[0] == '/': path = ''.join(where) print (path) continue path = get_new_path (path, where) if not path: path = ['/'] path = ''.join(path) print (path)
class Card(object): """ This class represents a standard card in a deck Each card consists of two attributes: value and suit There are 4 unique suits and 13 values """ def __init__(self, raw_card, value = None, suit = None): self.raw_card = raw_card self.value = self.get_value() self.suit = suit def get_value(self): """ Given a card string in format "[value][suit]", it will return the value of the card Ex: "10S" represents 10 of spades and will return the value 10 """ face_cards = ["J","Q","K"] ace = "A" value = self.raw_card[:len(self.raw_card) - 1] if value in face_cards: value = 10 if value == "A": value = 11 else: value = int(value) return value
from Tkinter import * def interface(account): window = Tk() window.geometry('450x220') window.title('Money Manager') app = App(window, account) window.mainloop() """ while on: refreshWindow() answer = raw_input("What would you like to do?\nAdd Transaction\nDeposit\nCheck Balance\nQuit\n\n") if (answer.split()[0]).lower() == "add": amount = input("How much was the transaction? ") account.addTransaction(amount) elif (answer.split()[0]).lower() == "deposit": amount = input("How much would you like to deposit? ") account.deposit(amount) elif (answer.split()[0]).lower() == "check": print (str(account.checkBalance()) + "\n") elif (answer.split()[0]).lower() == "quit": on = False account.quit() else: print ("Not a valid command. Try again.\n\n") """ class App: def __init__(self, window, account): self.account = account self.window= window self.amount = Label(self.window, fg="red", text = "$"+str(self.account.checkBalance())) self.amount.place(x=225, y=20) self.addButton = Button(self.window, text = "Add Transaction" , command = self.addTransactionInput) self.addButton.place(x=25, y=20) self.depositButton = Button(self.window, text = "Deposit" , command = self.depositInput) self.depositButton.place(x=25, y=70) self.balanceButton = Button(self.window, text = "Check Balance" , command = self.checkBalanceDialog) self.balanceButton.place(x=25, y=120) self.quitButton = Button(self.window, text = "Quit" , command = self.quitProgram) self.quitButton.place(x=25, y=170) self.entry = Entry(self.window) self.entry.place(x=225, y=120) self.entry.pack self.entry2 = Entry(self.window) self.submit = Button(self.window, text = "Submit", command=self.submit) def addTransactionInput(self): amount = int(self.entry.get()) self.entry2.place self.submit.place(x=225, y=170) self.entry.delete(0, END) self.entry.insert(0, "Thanks!") amount = self.submit print amount print "A transaction would be added" def submit(self): return self.entry2.get() def submitCategory(self): pass def depositInput(self): pass def checkBalanceDialog(self): print "balance would be checked" def quitProgram(self): self.account.quit() self.window.quit() if __name__ == '__main__': main()
hislist = ["apple", "banana", "cherry"] for x in hislist: print( x ); if "apple" in hislist: hislist.append("nova fruta") print( "Yes sim en lista" ); #Print the number of items in the list: print( len(hislist) ) #Using the append() method to append an item: hislist.append("nova fruta"); #Insert an item as the second position: hislist.insert(1, "orange") print(hislist) #The pop() method removes the specified index, (or the last item if index is not specified): hislist.pop() print(hislist) #The remove() method removes the specified item: hislist.remove("cherry") print(hislist) #The pop() method removes the specified index, (or the last item if index is not specified): hislist.pop() print(hislist) #The del keyword removes the specified index: del hislist[1]; print(hislist) #The del keyword can also delete the list completely: del hislist print(hislist)
import numpy as np # Matrix Operation Example W = np.array([[1, 2, 3], [4, 5, 6]]) X = np.array([[0, 1, 2], [3, 4, 5]]) print(W + X) print(W * X) # Broadcast Example A = np.array([[1, 2], [3, 4]]) b = np.array([10, 20]) print(A * b) # Vector Inner Product a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) print(np.dot(a, b)) # Matrix Product A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) print(np.matmul(A, B))
# 듣보잡 (https://www.acmicpc.net/problem/1764) import sys n,m = map(int, input().split()) #한줄에 입력값 받는 법 n_list = set([sys.stdin.readline().strip() for i in range(n)]) m_list =set([sys.stdin.readline().strip() for i in range(m)]) res = sorted(list(n_list&m_list)) print(len(res)) for i in res: print(i)
a = int(input("Enter a number :")) b = int(input("Enter second number :")) print("Which operation you would like to do....") print("press 0 for addition") print("press 1 for subtraction") print("press 2 for multiplication") print("press 3 for divison") x = int(input("Give the digit :")) if(x==0): sum = a+b print("Addition of both the numbers is :",sum) elif(x==1): subtraction = a-b print("Subtraction of both the numbers is :",subtraction) elif(x==2): multiplication = a*b print("Multiplication of both numbers is :",multiplication) elif(x==3): division = a/b print("Division of both numbers is :",division)
class Attribute: def __init__(self, attributeType, attributeName, lineStart): self.lineStart = lineStart self.attributeType = attributeType self.attributeName = attributeName def print(self): return "----------------------------------------------------------\n" + \ "{}:{}\n".format(self.attributeType, self.attributeName) + \ "Linhas:{}\n".format(self.lineStart)
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("output.csv") y = df[:9] y["x"] = y.index y_ = df[8:] y_["x"] = y_.index print(y) print(y_) plt.plot(y["x"], y["target"], "r-") plt.plot(y_["x"], y_["target"], color="blue") plt.show()
""" PyBank HW Checklist: 1. Import CSV File (budget_data.csv) 1a. Open and Read CSV File 2. Print (Financial Analysis) 3. Print (----------------------------) 4. Calculate: The total number of months included in the dataset 4a. Print (Total Months: 86) 5. Calculate: The total net amount of "Profit/Losses" over the entire period 5a. Print (Total: $38382578) 6. Calculate: The average change in "Profit/Losses" between months over the entire period 6a. Print (Average Change: $-2315.12) 7. Calculate: The greatest increase in profits (date and amount) over the entire period 7a. Print (Greatest Increase in Profits: Feb-2012 ($1926159)) 8. Calculate: The greatest decrease in losses (date and amount) over the entire period 8a. Print (Greatest Decrease in Profits: Sep-2013 ($-2196167)) 9**. Your final script should both print the analysis to the terminal 10**. Export a text file with the results ** As an example, your analysis should look similar to the one below: Financial Analysis ---------------------------- Total Months: 86 Total: $38382578 Average Change: $-2315.12 Greatest Increase in Profits: Feb-2012 ($1926159) Greatest Decrease in Profits: Sep-2013 ($-2196167) """ #1. Import & Read CSV File (budget_data.csv) import os import csv csvpath = os.path.join("budget_data.csv") #csv file in quotes because csv file is copied to same folder that contains main.py (current file) #2. Print (Financial Analysis) Financial_Analysis = ("Financial Analysis") print(Financial_Analysis) #3. Print (----------------------------) Break_Lines = ("--------------------------") print(Break_Lines) #1a. Open and Read CSV File with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile,delimiter=",") #4. Calculate: The total number of months included in the dataset #Count lines of csv. Each csv line (minus header) = one month next(csvfile) #skip count of the header row of csv file (approach #1) row_count = sum(1 for line in csvreader) Total_Months = ("Total Months: " + str(row_count)) #4a. Print (Total Months: 86) print(Total_Months) #Difficulty returning results; open/read csv file again. Indentation/block issue? with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") #5. Calculate: The total net amount of "Profit/Losses" over the entire period #Create variable list to hold all 'Profit/Losses' values net_profit_list = [] #Populate the list(net_profit_list): Loop through csv to grab only the 'Profit/Losses' column values of csv. Add to list(net_profit_list) for rows in csvreader: net_profit_list.append(rows[1]) net_profit_list.remove('Profit/Losses') #Remove the header (approach #2) #Convert list elements into integers so we can sum(net_profit_list) net_profit_list = [int(rows) for rows in net_profit_list] #print(net_profit_list[0:9]) #Create variable to house sum(net_profit_list) total_net_value = str(sum(net_profit_list)) Total_Net = (f"Total: ${total_net_value}") #5a. Print (Total: $38382578) print(Total_Net) # Second approach that successfully calculates sum(net_profit_list) #def listsum(net_profit_list): # theSum = 0 #for x in net_profit_list: # theSum = theSum + x # return theSum #print(listsum(net_profit_list)) #6. Calculate: The average change in "Profit/Losses" between months over the entire period """ Approach 1. Create a formula to find the change in Profit/Losses between each month over the entire period 2. To find the change between each month, I will want to: 2a. subtract the first element (first month profit/loss) in the list from the second element (second month profit/loss) 2b. subtract the second element from the third element 2c. and so forth, continuing this pattern, iterating over the entire list of net_profit_list 2a-c: Visually, I'm thinking this will look something like: [(2ndElement=2ndMonthValue=y)-(1stElement=1stMonthValue=x)] 2d. Then I want to store all the Profit/Losses between months in a new variable list (I'll call this list "res" for fun) 3. Calculate average of res = [the list of changes in Profit/Losses between months over the entire period] 3a. Calculate the count of the number of Profit/Losses in res 3b. Calculate the sum of the Profit/Losses in res 3c. Calculate the average change of Profit/Losses between months over the entire period 3a-c. Visually, I'm thinking (3b/3a)=(sum(res)/count(res))=avg(3b)=mean(3b) 4. Create a variable to store the average change of Profit/Losses between months over the entire period """ #Approach 1, 2a-d Formula res = [y - x for x, y in zip(net_profit_list, net_profit_list[1:])] #print(net_profit_list) #print(net_profit_list[1:]) #print(res) #Approach 3a-c import statistics #Approach 4 x = statistics.mean(res) Average_Change = (f"Average Change: ${round(x,2)}") #round(x,2) returns a rounded number to the second decimal point #6a. Print (Average Change: $-2315.12) print(Average_Change) #7. Calculate: The greatest increase in profits (date and amount) over the entire period #8. Calculate: The greatest decrease in losses (date and amount) over the entire period """ Approach_Profits: 1. Identify the integer with the (max_value=highest value) in res = [the list of changes in Profit/Losses between months over the entire period] 2. Identify the integer with the (min_value=lowest value) in res = [the list of changes in Profit/Losses between months over the entire period] 3. Create a variable list to house only the csv 'Date' column values (minus the header) *I think I could also delete the second row of csv 'Date' col as the month change begins with the second month *this would change the formula I have slightly if I were to implement, but good to keep in mind 4. Join (or zip) the separate lists: zip(4aList+4bList) 4a.res = [the list of changes in Profit/Losses between months over the entire period] + 4b. net_profit_plus_month = [the list of months in the 'Date' col minus header] 4c. Pair the month value with the corresponding max_value or min_value 5. Identify each respective min/max value with the corresponding month """ with open(csvpath, newline="") as csvfile: #Difficulty with return results (again); open file csvreader = csv.reader(csvfile, delimiter=",") #Approach_Profits 3 net_profit_plus_month = [] #Create list variable to house csv 'Date' column for rows in csvreader: net_profit_plus_month.append(rows[0:1]) #Adds all months to list net_profit_plus_month.pop(0) #Remove the 'Date' header (approach #3) net_profit_plus_month_n = [i[0] for i in net_profit_plus_month] #Converts list to (string?) return "Jan 2016" instead of "('Jan 2016')" per value with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") #Approach_Profits 1 & 2 max_value = max(res) #Max value of the Profit/Losses between months average list (res) min_value = min(res) #Min value of the Profit/Losses between months average list (res) with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") #Approach_Profits 4 result = [None]*(len(net_profit_plus_month_n)+len(res)) #"list by index": Assigns index #s to each list result[::2] = net_profit_plus_month_n #retain index order of each list; Profit/Losses match with month result[1::2] = res #Approach_Profits 5 for x, y in zip(result, result[1:]): #Assign x to Profit/Losses; Assign y to month value if x == max_value: #If Profit/Loss matches with the determined max value Greatest_Increase = ("Greatest Increase in Profits: " + str(y) + " ("+str(x) +")") if x == min_value: #If Profit/Loss matches with the determined min value Greatest_Decrease = ("Greatest Decrease in Profits: " + str(y) + " ("+str(x) +")") #7a. Print (Greatest Increase in Profits: Feb-2012 ($1926159)) print(Greatest_Increase) #8a. Print (Greatest Decrease in Profits: Sep-2013 ($-2196167)) print(Greatest_Decrease) print() #9**. Your final script should both print the analysis to the terminal #10**. Export a text file with the results #I ask the user if they'd like to create and export a text file of the results, just to be nice and polite and stuff. Output_Text = input("Would you like to export a text file of the results? If yes, type 'y':") if Output_Text == 'y': print("Okay, a text file of the results has been exported as 'pythonhw1-pybank-results-2018.txt'") f = open('pythonhw1-pybank-results-2018.txt','w') f.write(Financial_Analysis + "\n" + Break_Lines + "\n" + Total_Months + "\n" + Total_Net + "\n" + Average_Change + "\n" + Greatest_Increase + "\n" + Greatest_Decrease ) f.close() else: print("Okay, a text file of the results will *not* be exported :)")
s = str(raw_input()) if s.isupper(): print s.lower() exit (0)
s1 = list(str(raw_input()).lower()) s2 = list(str(raw_input()).lower()) if s1 == s2 : print '0' elif s2 > s1: print '-1' elif s1 > s2: print '1'
def format_input(): meal = [] recipe = raw_input("Recipe name: ") recipe_mats = raw_input("Ingredients, separated by commas: ") recipe = recipe.replace(' ','_') meal.append(recipe+' =') meal.append(recipe_mats.split(', ')) return meal # append string (imitating list) to ingredients file def write_new(): f = open('lonelypantry_ingredients.py', 'a') f.write('\n'+str(format_input())) f.close() print "Recipe added to lonelypantry_ingredients.py successfully." add_another() def add_another(): repeat = raw_input("Add another? y / n: ") if repeat == 'y': write_new() elif repeat == 'n': sys.exit() else: print "Sorry, I didn't understand you. Please press y or n followed by\ enter." add_another() write_new()
# Binary Tree implementation using List # Create Traverse Search Insert Delete # Binary tree has always at most 2 children # Creating is O(n), rest is O(1) # Linked list Insert is O(n) but also spcae complexity is O(n) class BinaryTree: def __init__(self, size): self.customList = size * [None] self.last_used_index = 0 self.capacity = size def insertNode(self, value): if self.last_used_index + 1 == self.capacity: return "Binary Tree is full" self.custom_list[self.last_used_index+1] = value self.last_used_index += 1 return "Inserted" def searchNode(self, nodeValue): for i in range(len(self.custom_list)): if self.custom_list[i] == nodeValue: return "Success" return "Not found" def preOrderTraversal(self, index): if index > self.last_used_index: return print(self.custom_list[index]) self.preOrderTraversal(index*2) self.preOrderTraversal(index*2 + 1) def inOrderTraversal(self, index): if index > self.last_used_index: return self.inOrderTraversal(index*2) print(self.custom_list[index]) self.inOrderTraversal(index*2+1) def postOrderTraversal(self, index): if index > self.last_used_index: return self.postOrderTraversal(index*2) self.postOrderTraversal(index*2+1) print(self.custom_list[index]) def levelOrderTraversal(self, index): for i in range(index, self.last_used_index+1): print(self.custom_list[i]) def deleteNode(self, value): if self.last_used_index == 0: return "There is not any node to delete" for i in range(1, self.last_used_index+1): if self.custom_list[i] == value: self.custom_list[i] = self.custom_list[self.last_used_index] self.custom_list[self.last_used_index] = None self.last_used_index -= 1 return "Deleted" def deleteBinaryTree(self): self.custom_list = None return "Deleted"
import math from array import array print("hello"); print('mosh hamedani is my best youtube instructor') name = "Muwonge lawrence the programmer" age = 20 print('*' * 10) print(f'my name is {name} and my age is {age} so you are welcome to python programming.') print('*' * 10) print("3 squared is " + str(3 ** 2)) print("-" * 50) print("lets draw a right angled triangle") for i in range(8): print("*" * i) print('lets implement a sqaure') for j in range(4): print("*" * 4) print('lets implement a heart') for j in range(1, 6): if j == 2: continue elif j == 3: print("-" * j) # break else: print("*" * j) else: print("attempted all the times.") message = """ hi muwonge this is lawrence the fullstack developer how are you doing these days. """ course = "python Programming" newString = course[:] full = f"{message} \n l am learning {newString}" print(full) # print(newString) print("The length of the above string is " + str(len(message))) # ceil of the values . print(math.ceil(2.2)) x = input("x:") y = int(x) + 9 print(f"x: {x} , y:{y}") # working with comparison operators age = 22 message = "Eligible" if age >= 18 else "Not Eligible" print(message) print(type(5)) # infinite loops while True: command = input(">:") print("Echo", command) if command.lower() == "quit": break # using the zip function list1 = [1, 2, 3] list2 = [10, 20, 30] print(list(zip(list1, list2))) # swapping variables in python x = 10 y = 11 x, y = y, x print("x:", x) print("y:", y) # use of Arrays in python numbers = array("i", [1, 2, 3]) print("This is from an array", numbers)
entradaTeclado = int(input("Entre com um valor \n")) for num in range(entradaTeclado + 1): #conta de zero a cem divisao = 0 for cont in range(1, num + 1): #contador aninhado restoDivisao = num % cont #resto if restoDivisao == 0: divisao += 1 if divisao == 2: print(num) #imprime apenas os numeros primos
#Exercicios bimestre notaAprovado = 50 notaReprovado = 49 mensagemAprovado = "Parabéns voçê foi aprovado!!!" mensagemReprovado = "Voçê não foi aprovado, se dedique um pouco mais ano que vem!!!!" nomeAluno = str(input("Nome do Aluno ? \n")) #Nota do primeiro bimestre nota1 = float(input("Lançe a nota do 1º Bimestre \n")) while nota1 > 100: nota1 = float(input("Lance a nota do 1º Bimestre corretamente \n")) #Nota do segundo bimestre nota2 = float(input("Lance a nota do 2º Bimestre \n")) while nota2 > 100: nota2 = float(input("Lance a nota do 2º Bimestre, corretamente \n")) # Nota do terceiro bimestre nota3 = float(input("Lance a nota do 3º Bimestre \n")) while nota3 > 100: nota3 = float(input("Lance a nota do 3º Bimestre, corretamente \n")) #Nota do quarto bimestre nota4 = float(input("Lance a nota do 4º Bimestre \n")) while nota4 > 100: nota4 = float(input("Lance a nota do 4º Bimestre, corretamente \n")) #soma de todas as notas somaNotas = (nota1 + nota2 + nota3 + nota4) / 4 if somaNotas > notaReprovado: print('{}'.format(somaNotas)) print(nomeAluno, "\n", mensagemAprovado) else: print('somaNotas:{resultado}'.format(resultado=somaNotas)) print(nomeAluno, ", ", mensagemReprovado)
class Matrix: def mul(x,y): #self? if(len(x[0]) != len(y)): print('ValueError') else: result = [] for i in range(len(x)): temp = [] for j in range(len(y[0])) : temp2 = 0 for k in range(len(y)) : temp2 += x[i][k]*y[k][j] temp.append(temp2) result.append(temp) print('success!') return result l = [[1,2,3],[4,5,6]] m = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] print(Matrix.mul(l,m))
import sys def is_palindrome(s): num_s = len(s) for i in range(num_s / 2): if s[i] != s[num_s - 1 - i]: print "FAIL" sys.exit() print "PASS" if __name__ == "__main__": s_1 = ["a", "b", "c", "b", "a"] s_2 = ["a", "b", "c", "a", "b"] is_palindrome(s_1) is_palindrome(s_2)
# method 1 def shift_first_char(s): num = len(s) temp = s[0] for i in range(num - 1): s[i] = s[i + 1] s[num - 1] = temp def shift_char(s, n): for i in range(n): shift_first_char(s) print s # method 2 def shift_char_2(s, n): num = len(s) temp = [] for i in range(n): temp.append(s[i]) for i in range(num - n): s[i] = s[i + n] for i in range(n): s.append(temp[i]) print s # method 3 def reverse(s, begin, end): num = end - begin for i in range(num / 2): temp = s[begin + i] s[begin + i] = s[end - 1 - i] s[end - 1 - i] = temp # print s def three_step_rotate(s, n): num = len(s) # it will generate new list, can not satisfy # reverse(s[0:n]) # reverse(s[n + 1:num]) reverse(s, 0, n) reverse(s, n, num) reverse(s, 0, num) print s if __name__ == "__main__": string = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] # shift_char(string, 3) # shift_char_2(string, 4) # reverse(string, 2, 10) three_step_rotate(string, 5)
for n in range(1, 101): output = "" if n % 3 == 0: output = output + "Fizz" if n % 5 == 0: output = output + "Buzz" if output == "": output = n print output
import farkle import position from itertools import chain, combinations import random from time import sleep class RandomPolicy: def __init__(self, name, verbose=False): self.name = name self.verbose = verbose def get_name(self): return self.name def start_turn(self, game, pos): """ Displays the scoresheet at the start of a turn. game -- the game this policy is playing pos -- a position in that game """ if self.verbose: print(chr(27) + "[2J") print(f"{self.name}'s turn:") print("_" * (len(self.name) + 10)) print() game.display_scores() def see_roll(self, game, pos): """ Displays the current roll. game -- the game this policy is playing pos -- a position in that game """ if self.verbose: game.diceroll.print_roll() game.diceroll.print_aside() print() def powerset(self, roll): """ powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) """ return set(chain.from_iterable(combinations(roll, r) for r in range(len(roll)+1))) def random_keep(self, game, pos): roll = game.diceroll.get_roll() possible_keeps = self.powerset(roll) valid_keeps = [] for keep in possible_keeps: keep = list(keep) if game.valid_keep(keep): valid_keeps.append(keep) return random.choice(valid_keeps) def choose_dice(self, game, pos): """ Returns the dice to keep in in the given position in the given game. The dice are read from standard input as digits with no spaces in between. The dice to keep are returned as a DiceRoll that is a subset of the roll in the given position. game -- the game this policy is playing pos -- a position in that game """ keep = self.random_keep(game, pos) if self.verbose: print(f"Enter dice to keep: {''.join(keep)}") sleep(4) return keep def choose_action(self, game, pos): """ After the player chooses which dice to keep, they have a choice of either ending their turn and banking their score or continue their turn by rerolling. """ actions = ['b', 'r'] action = random.choice(actions) if self.verbose == True: print(f"Bank(b) or Reroll(r)?: {action}") sleep(3) return action
class Dequeue: DEFAULT_CAPACITY = 10 def __init__(self): self.data = [None] * Dequeue.DEFAULT_CAPACITY self.size = 0 self.front = 0 def __len__(self): return self.size def is_empty(self): return (self.size == 0) def first(self): if self.is_empty(): raise ('Queue is empty') return self.data[self.front] def last(self): back = (self.front + self.size - 1) % len(self.data) return self.data[back] def add_first(self, item): if self.size == len(self.data): self.resize(2*len(self.data)) avail = (self.front - 1) % len(self.data) self.data[avail] = item self.front = (self.front - 1) % len(self.data) self.size += 1 def add_last(self, item): if self.size == len(self.data): self.resize(2*len(self.data)) avail = (self.front + self.size) % len(self.data) self.data [avail] = item self.size += 1 def delete_first(self): if (self.is_empty()): raise Empty("Queue is empty") value = self.data[self.front] self.data[self.front] = None self.front = (self.front + 1) % len(self.data) self.size -= 1 if(self.size < len(self.data) // 4): self.resize(len(self.data) // 2) self.data[self.front] = None self.size -= 1 return value def delete_last(self): back_ind = ((self.front + self.size) % len(self.data)) - 1 value = self.data[back_ind] self.data[back_ind] = None self.size -= 1 return value def resize(self, new_cap): old_data = self.data self.data = [None] * new_cap old_ind = self.front for new_ind in range(self.size): self.data[new_ind] = old_data[old_ind] old_ind = (old_ind + 1) % len(old_data) self.front = 0
def split_parity(lst): switch1 = 0 switch2 = 0 for i in lst: #O(n) if i % 2 == 1: #if odd... lst[switch1], lst[switch2] = lst[switch2], lst[switch1] switch1 = switch1 + 1 switch2 = switch2 + 1 if i % 2 == 0: #if even switch2 = switch2 + 1 return lst ''' [1,2,3,4,5] check 0th index... If it is odd... Increase both index... switch1 & 2 = 1 If it is even... switch 2 ++... if it is odd... switch 1 and 2... ''' input = [3,9,6,4,6,12,13] print("Original Input:" + str(input)) print("Final Output:" + str(split_parity(input)))
class EmptyTree(Exception): pass class LinkedBinaryTree: class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.left = left if (self.left is not None): self.left.parent = self self.right = right if (self.right is not None): self.right.parent = self self.parent = None def __init__(self, root=None): self.root = root self.size = self.subtree_count(self.root) def __len__(self): return self.size def is_empty(self): return (len(self) == 0) def subtree_count(self, subtree_root): if(subtree_root is None): return 0 else: left_count = self.subtree_count(subtree_root.left) right_count = self.subtree_count(subtree_root.right) return left_count + right_count + 1 def sum_tree(self): return self.subtree_sum(self.root) def subtree_sum(self, subtree_root): if(subtree_root is None): return 0 else: left_sum = self.subtree_sum(subtree_root.left) right_sum = self.subtree_sum(subtree_root.right) return left_sum + right_sum + subtree_root.data def height(self): if (self.is_empty()): raise EmptyTree("Height is not defined for an empty tree") return self.subtree_height(self.root) #assuming subtree_root is not empty def subtree_height(self, subtree_root): if (subtree_root.left is None) and (subtree_root.right is None): return 0 elif subtree_root.left is None or subtree_root.right is None: if subtree_root.left is None: return 1 + self.subtree_height(subtree_root.right) else: return 1 + self.subtree_height(subtree_root.left) else: left_height = self.subtree_height(subtree_root.left) right_height = self.subtree_height(subtree_root.right) return 1 + max(left_height, right_height) def preorder(self): yield from self.subtree_inorder(self.root) def subtree_preorder(self, subtree_root): if subtree_root is None: return else: yield subtree_root yield from self.subtree_preorder(subtree_root.left) yield from self.subtree_preorder(subtree_root.right) def preorder2(self): yield from self.subtree_inorder(self.root) def subtree_preorder(self, subtree_root): if subtree_root is None: return else: print(subtree_root) self.subtree_preorder(subtree_root.left) self.subtree_preorder(subtree_root.right) def postorder(self): yield from self.subtree_postorder(self.root) def subtree_postorder(self, subtree_root): if subtree_root is None: return else: yield from self.subtree_postorder(subtree_root.left) yield from self.subtree_postorder(subtree_root.right) yield subtree_root def iterative_inorder(self): current = self.root while current is not None: if current.left is None: yield current.data current = current.right else: pred = current.left while pred.right is not None and pred.right != current: pred = pred.right if pred.right is None: pred.right = current current = current.left else: pred.right = None yield current.data current = current.right def inorder(self): yield from self.subtree_inorder(self.root) def subtree_inorder(self, subtree_root): if subtree_root is None: return else: yield from self.subtree_inorder(subtree_root.left) yield subtree_root yield from self.subtree_inorder(subtree_root.right) def __iter__(self): for node in self.inorder(): yield node.data def leaves_list(self): if self.root == None: return [] return self.leaves_list_helper(self.root, []) def leaves_list_helper(self, subtree_root, leaves, firstTime = None): #EDGE CASE if firstTime is None: if subtree_root is not None and subtree_root.left is None and subtree_root.right is None: return [subtree_root.data] else: firstTime = False #BASE CASE if subtree_root.left is None and subtree_root.right is None: leaves.append(subtree_root.data) if subtree_root.left is not None: self.leaves_list_helper(subtree_root.left, leaves, firstTime) if subtree_root.right is not None: self.leaves_list_helper(subtree_root.right, leaves, firstTime) return leaves def min_and_max(bin_tree): if bin_tree.root is None: raise EmptyTree if bin_tree.root.left is None and bin_tree.root.right is None: tup = bin_tree.root.data, bin_tree.root.data return tup def subtree_min_and_max(bin_tree, subtree_root): if (subtree_root.left is None and subtree_root.right is None): return subtree_root.data else: if subtree_root.left is not None: left_sum = subtree_min_and_max(bin_tree, subtree_root.left) check = subtree_root.data if type(left_sum) is int: if check < left_sum: left_sum = (check, left_sum) else: left_sum = (left_sum, check) else: if check < left_sum[0]: left_sum = (check, left_sum[1]) if check > left_sum[1]: left_sum = (left_sum[0], check) else: left_sum = subtree_root.data if subtree_root.right is not None: right_sum = subtree_min_and_max(bin_tree, subtree_root.right) check = subtree_root.data if type(right_sum) is int: if check < right_sum: right_sum = (check, right_sum) else: right_sum = (right_sum, check) else: if check < right_sum[0]: right_sum = (check, right_sum[1]) if check > right_sum[1]: right_sum = (right_sum[0], check) else: right_sum = subtree_root.data if isinstance(right_sum, int) and isinstance(left_sum, int): # If both of the comparisons are integer... if left_sum > right_sum: # If the left side of the branch is bigger, than, return... tuple = (right_sum, left_sum) # Min, Max return tuple if right_sum > left_sum: # If left side is smaller, return... tuple = (left_sum, right_sum) # Min, max return tuple elif type(left_sum) is not int and type( right_sum) is int: # If the left side is a tuple.. but right side isn't... # Compare the right versus both the min of the tuple and max of the tuple minTuple = left_sum[0] maxTuple = left_sum[1] newTuple = (minTuple, maxTuple) if right_sum < minTuple: newTuple = (right_sum, maxTuple) if right_sum > maxTuple: newTuple = (minTuple, right_sum) return newTuple if type(left_sum) is int and type( right_sum) is not int: # If the right side is a tuple.. but left side isn't... # Compare the left_sum versus both the min of the tuple and max of the tuple minTuple = right_sum[0] maxTuple = right_sum[1] newTuple = (minTuple, maxTuple) if left_sum < minTuple: newTuple = (left_sum, maxTuple) if left_sum > maxTuple: newTuple = (minTuple, left_sum) return newTuple else: # If both are tuples... compare each min and max... leftMin = left_sum[0] rightMin = right_sum[0] leftMax = left_sum[1] rightMax = right_sum[1] newMin = 0 newMax = 0 if leftMin < rightMin: newMin = leftMin else: newMin = rightMin if leftMax > rightMax: newMax = leftMax else: newMax = rightMax newTuple = (newMin, newMax) return newTuple root = bin_tree.root #HELPER FUNCTION return subtree_min_and_max(bin_tree, root) def is_height_balanced(bin_tree): root = bin_tree.root return sub_balanced(root) >= 0 def sub_balanced(root): if root is None: return 0; left = sub_balanced(root.left) right = sub_balanced(root.right) if left < 0 or right < 0 or abs(left - right) > 1: return -1 return max(left, right) + 1 def create_expression_tree(prefix_exp_str): lst = prefix_exp_str.split(' ') output = subcreate_tree(lst, 0) return LinkedBinaryTree(output[0]) def subcreate_tree(lst, index): if lst[index].isdigit(): intVersion = int(lst[index]) return LinkedBinaryTree.Node(intVersion), 1 else: left = subcreate_tree(lst, index + 1) right = subcreate_tree(lst, index + left[1] + 1) return LinkedBinaryTree.Node(lst[index], left[0], right[0]), left[1] + right[1] + 1 def prefix_to_postfix(prefix_exp_str): tree = create_expression_tree(prefix_exp_str) ouput = [] for item in tree.postorder(): ouput.append(str(item.data)) return ' '.join(ouput) c=LinkedBinaryTree.Node(5) d=LinkedBinaryTree.Node(1) e=LinkedBinaryTree.Node(8,c,d) f=LinkedBinaryTree.Node(4) g=LinkedBinaryTree.Node(7,e,f) h=LinkedBinaryTree.Node(9) i=LinkedBinaryTree.Node(2,h) j=LinkedBinaryTree.Node(3,i,g) treee=LinkedBinaryTree(j) for i in treee.preorder(): print (i.data) for l in treee.preorder2(): print(l.data)
# Question 5 # # PERMUTATIONS FUNCTION IS LOCATED BELOW IN FILE! # class Empty(Exception): pass class ArrayStack: def __init__(self): self.data = [] def __len__(self): return len(self.data) def is_empty(self): return len(self) == 0 def push(self, val): self.data.append(val) def top(self): if (self.is_empty()): raise Empty("Stack is empty") return self.data[-1] def pop(self): if (self.is_empty()): raise Empty("Stack is empty") return self.data.pop() class ArrayQueue: INITIAL_CAPACITY = 10 def __init__(self): self.data = [None] * ArrayQueue.INITIAL_CAPACITY self.num_of_elems = 0 self.front_ind = 0 def __len__(self): return self.num_of_elems def is_empty(self): return (self.num_of_elems == 0) def enqueue(self, elem): if (self.num_of_elems == len(self.data)): self.resize(2 * len(self.data)) back_ind = (self.front_ind + self.num_of_elems) % len(self.data) self.data[back_ind] = elem self.num_of_elems += 1 def dequeue(self): if (self.is_empty()): raise Empty("Queue is empty") value = self.data[self.front_ind] self.data[self.front_ind] = None self.front_ind = (self.front_ind + 1) % len(self.data) self.num_of_elems -= 1 if(self.num_of_elems < len(self.data) // 4): self.resize(len(self.data) // 2) return value def first(self): if self.is_empty(): raise Empty("Queue is empty") return self.data[self.front_ind] def resize(self, new_cap): old_data = self.data self.data = [None] * new_cap old_ind = self.front_ind for new_ind in range(self.num_of_elems): self.data[new_ind] = old_data[old_ind] old_ind = (old_ind + 1) % len(old_data) self.front_ind = 0 def permutations(lst): #given a list of integers, return a list containing all the permutations of that list. This function is non-recursive. import copy numbers_left = ArrayStack() answers = ArrayQueue() for elem in lst: #place all numbers into stack numbers_left.push(elem) while not numbers_left.is_empty(): if answers.is_empty(): #add in very first number as its permutation answers.enqueue([numbers_left.pop()]) else: single = numbers_left.pop() #isolate one number for a in range(len(answers)): #go through each list block in queue permutation = [answers.dequeue()] #list of list of numbers for ind in range(len(permutation)): #go into list within queue for i in range(len(permutation[ind])+1): #get index of the list within queue temp = copy.deepcopy(permutation[ind]) #make actual COPY, since insert() changes original temp.insert(i, single) answers.enqueue(temp) #insert permutation into enqueue return answers s = permutations([1, 2, 3, 4]) print('answers') while not s.is_empty(): print(s.dequeue())
def findchange(lst): highIndex = len(lst) - 1 lowIndex = 0 divideIndex = int((highIndex + lowIndex)/2) control = True # if(len(lst) == 2): # if(lst[1] == 1): # return 1 # else: # return "improper input, there needs to be 0s and 1s" # if(len(lst) == 1): # return "Insert a list larger than a size of 1" while(control): leftValue = lst[divideIndex -1] rightValue = lst[divideIndex + 1] if(leftValue == 0 and rightValue == 1): if(lst[divideIndex] == 0): return divideIndex + 1 else: return divideIndex + 0 elif (leftValue == 1 and rightValue == 1): highIndex = divideIndex divideIndex = int((lowIndex + highIndex)/2) elif(leftValue == 0 and rightValue == 0): lowIndex = divideIndex divideIndex = int((lowIndex + highIndex)/2) if(highIndex == lowIndex): control = False return "There needs to be 0s and 1s" input = [0,0,1,1,1,1,1,1,1,1,1,1,1] print(findchange(input)) input = [0,1,1,1,1,1,1,1,1,1,1,1,1] print(findchange(input)) input = [1,1,1,1,1,1,1,1,1,1,1,1,1] print(findchange(input)) input = [0,1] print(findchange(input)) input = [0,0,1,1] print(findchange(input)) ''' Initial Settings. Find the upperBound = lst.length - 1 LowerBound = 0 Then find the divide in between... Check Left and Right of the divide. if: right and left = 0, 1 return divide if: right and left = 1,1 high = divide divide = low + high / 2 if right and left = 0,0 low = divide divide = low + high / 2 '''
from cryptography.fernet import Fernet # Get existing Fernet key def get_fernet_key(): print("Enter Key:") key_str = input() key_bytes = key_str.encode() return Fernet(key_bytes) # Enter the encoded capture def get_encoded_capture(): print("\nEnter Capture:") capture_str = input() return capture_str.encode() # Decrypt and output the encrypted message def decrypt_message(key, encoded_message): print("\nMessage:") print(key.decrypt(encoded_message).decode()) if __name__ == "__main__": f = get_fernet_key() capture_bytes = get_encoded_capture() decrypt_message(key=f, encoded_message=capture_bytes)
#!/usr/bin/env python # ----------------------------------- # remove files in each subfolder in the given path starting from the given indices # Author: Tao Chen # Date: 2016.10.16 # ----------------------------------- import os import sys import numbers import re def rm_riles(path, index): if not os.path.exists(path): print 'path you entered did not exist.' return folder_lst = os.listdir(path) for foldername in folder_lst: folder_dir = os.path.join(path, foldername) files_lst = os.listdir(folder_dir) for filename in files_lst: fileindex_list = re.findall(r'\d+', filename) fileindex = int(fileindex_list[0]) if fileindex >= index: try: os.remove(os.path.join(folder_dir,filename)) except OSError, e: print 'remove file error' print e print 'deleting files done...' if __name__ == "__main__": dir = raw_input("please enter the full path of the directory: ") if dir == '\x03' or dir == '\x71': # ctrl + c or 'q' sys.exit() index_inputed = False while not index_inputed: index = raw_input("please enter the starting index of the file that you wanna delete: ") if index == '\x03' or index == '\x71': # ctrl + c or 'q' sys.exit() try: index = eval(index) if not isinstance(index, numbers.Integral): print "index is not an integer" print "Please enter it again..." else: print "you entered index = ", index index_inputed = True except NameError, e: print "You did not enter a number, please try again" rm_riles(dir, index)
# 4. Days Calculator from datetime import datetime print("Date format dd/mm/yy") date1 = input("enter 1st date:") date2 = input("enter 2nd date:") date_format = "%d/%m/%Y" a = datetime.strptime(date1, date_format) b = datetime.strptime(date2, date_format) delta = b - a x = (delta.days) print("There are ", x, " days in between", date1 ," and ",date2 )
# 10. Calculate Interest amount = int(input("Please enter principal amount:")) rate = float(input("Please Enter Rate of interest in %:")) years = int(input("Enter number of years for investment:")) cal = (amount*(1+rate/100)**years) print("After", years, "years your principal amount", amount, "over an interest rate of", rate, "% will be", cal)
# 9. Triangle area base = float(input("ENTER BASE:")) height = float(input("ENTER HEIGHT:")) area = 1/2*(base*height) print("Area of a Triangle with Height", height, "and Base", base, "is", area )
''' Text Based Seek Steering Behavior ''' import math import time from datetime import timedelta print("Implementing Seek Steering Behaviors...") print("\n") #The Player Class class player: def __init__(self, x, y): self.x = float(x) self.y = float(y) def current_position(self): return self.x, self.y def move_player_position(x, y): self.x = x self.y = x def get_position_x(self): return self.x def get_position_y(self): return self.y #The NPC class npc: def __init__(self, x, y): self.x = x self.y = y self.target_x = 0 self.target_y = 0 self.velocity_vector = [0,0] def get_x_coordinate(self): return self.x def get_y_coordinate(self): return self.y def set_target(self, px, py): self.target_x = px self.target_y = py def get_npc_velocity(self): #find the NPC velocity which is the hypotenuse self.velocity_vector[0] = self.target_x - self.get_x_coordinate() self.velocity_vector[1] = self.target_y - self.get_y_coordinate() return self.velocity_vector def get_euler_position(self): print("Velocity vector {0}".format(self.velocity_vector)) self.x = self.x + self.get_npc_velocity()[0] self.y = self.y + self.get_npc_velocity()[1] print("NPC Position position:({0}, {1}) ".format(self.x, self.y)) def current_position(self): return self.x, self.y def update(dtime): current_time = time.time() if current_time > dtime: game() def game(): print("Please press C to change your coordinates at any time.") print("PLAYERChar please initialize your coordinates:") x = input("x-coordinate:") y = input("y-coordinate:") #create the player object p = player(x, y) #get the player's current position p.current_position() #initialize the npc n = npc(3,5) print ("Player position : NPC Target {0}".format(p.current_position())) print("NPC starting position {0}".format(n.current_position())) #give the NPC the target position n.set_target(p.get_position_x(), p.get_position_y()) #keep moving until the npc arrives at target while(n.current_position() < p.current_position()): #keep moving npc n.get_euler_position() def main(): d_time = time.time() update(d_time) print("Seek Steering Behavior Text Tutorial") if __name__ == "__main__": main()
import os import csv #creating path to collect data from the my PyBank Folder budget_data = os.path.join('budget_file.csv') #delcare variables that will be used throughout program total_months = 0 #int value to hold number of months total_profit = 0 #int value to hold value of profit value = 0 #int variable that will hold the value for each row change = 0 #int variable that will store the change in value from each row profit = [] #list variable that will store the list of a row months = [] #same instance but for the months in the row #Reading in the csv file that we are working with with open(budget_data) as csvfile: #splittin gth edata with a comma delimiter reader = csv.reader(csvfile, delimiter=",") #Telling the program to skep the heaader values header = next(reader) #Setting a variable first_value = to the first row with will a value first_value = next(reader) #Setting the a variable total_profit = the long value in the data set total_profit += int(first_value[1]) #Same instance for value value += int(first_value[1]) #initiating for loop to read through the values of the csv file for row in reader: #Appending the values in the 1st column to my variable months months.append(row[0]) #Running a calculation within the for loop that will keep track of the #change in value throughout the data set #it is subtracting the first value from the upcoming second value within the loop change = int(row[1]) - value profit.append(change) value = int(row[1]) #counter int variable that is storing the total value of months within the data set total_months += 1 #Grabbing the total sum of the data set total_profit = total_profit + int(row[1]) #exit the for loop by indentation #Finding the max profit within the data set #Python is locating the max value change and storing the value in the large_increase variable large_increase = max(profit) #Creating an index for the location of which this max profit takes place large_index = profit.index(large_increase) #Using the index created to find the date for which this occurs within the data set large_date = months[large_index] #Same instance for the largest decrease in profits large_decrease = min(profit) decrease_index = profit.index(large_decrease) decrease_date = months[decrease_index] #finding the average of the change with the new values that were found from tracking the total #change of values #storing this value in variable average_change #we are using the sum and length function to perform this calculation average_change = sum(profit)/len(profit) #Printing the Analysis for the user #using a round function to round the average change to the nearest 2 decimal places print(f"Financial Analysis") print(f"-----------------------") print(f"Total Months: {(total_months)}") print(f"Total: ${total_profit}") print(f"Average Change: ${str(round(average_change,2))}") print(f"Greatest Increase in Profits: {large_date} (${large_increase})") print(f"Greatest Decrease in Profits: {decrease_date} (${large_decrease})") #opening the output file with the newly summarized and formatted data output_data = os.path.join("Analyzed_Data.csv") with open(output_data, "w") as writer: #writing out to the data to the csv file writer.write(f"Financial Analysis") writer.write(f"\n----------------------------------") writer.write(f"\n") writer.write(f"Total Months: {total_months}") writer.write(f"\n\n") writer.write(f"Total: ${total_profit}") writer.write(f"\n\n") writer.write(f"Average Change: ${str(round(average_change,2))}") writer.write(f"\n\n") writer.write(f"Greatest Increase in Profits: {large_date} (${large_increase})") writer.write(f"\n\n") writer.write(f"Greatest Decrease in Profits: {decrease_date} (${large_decrease})")
import numpy as np import math import matplotlib.pyplot as plt import matplotlib as mpl def neuronio(x, weights): activation = weights[-1] for i in range(len(weights)-1): activation += weights[i] * x[i+2] return activation def training_weights(train): error=0.0 sum_error =1 epoch=1 while(sum_error/15>0.0001 and epoch<10000): epoch += 1 sum_error = 0 for row in train: error = row[-1]-neuronio(row,weight) weight[-1] = weight[-1] + step * error sum_error+= error**2 for i in range(len(weight)-1): weight[i] = weight[i] + step * error * row[i+2] print("Epocas: "+str(epoch)) # print(weight) def training_weights_bateladas(train): error = 1.0 epoch=0 p = len(train) while(error/p>0.000001 and epoch<100000): sum_error = [0.0, 0.0, 0.0] error = 0.0 lim_error = 0.0 p=0 epoch+=1 for row in train: error = row[-1] - neuronio(row, weight) lim_error += step * error for i in range(len(weight)-1): sum_error[i] = sum_error[i] + step * error * row[i + 2] p+=1 for i in range(len(weight)-1): weight[i] = weight[i] + sum_error[i]/p error += sum_error[i]**2 weight[-1] = weight[-1] + lim_error/p print("Epocas: " + str(epoch)) # print(weight) def test_validacao(): dataset_treinamento =create_dataset(0, 2 * np.pi, 30) dataset_validacao = create_dataset(0.32, 2.1 * np.pi, 10) error =[] index=0 result_test=[] training_weights_bateladas(dataset_treinamento) weight_batelada = weight[:] z1 = np.linspace(0.32, 2.1 * np.pi, 10) f = (-1) * np.pi + 0.565 * np.sin(z1) + 2.674 * np.cos(z1) + 0.674 * z1 for row in dataset_validacao: result_test.append(neuronio(row, weight_batelada)) error.append(math.sqrt((f[index]-neuronio(row, weight_batelada))**2)) index += 1 print(max(error)) plt.figure(2) plt.plot(z1, f,label='f(z)') plt.plot(z1, result_test, label='Resuldado treinamento') plt.plot(z1, error, label='Erro trinemento e f(z)') plt.legend() plt.show() def create_dataset(init,end,qtd): z1 = np.linspace(init,end,qtd) dataset_test = [] for k in range(len(z1)): x_1 = np.sin(z1[k]) x_2 = np.cos(z1[k]) x_3 = z1[k] f = (-1) * np.pi + 0.565 * x_1 + 2.674 * x_2 + 0.674 * x_3 dat = [k + 1, round(z1[k], 3), round(x_1, 3), round(x_2, 3), round(x_3, 3), round(f, 3)] print(dat) dataset_test.append(dat) dataset=[] z = np.linspace(0, 2*np.pi, 15) for k in range(len(z)): x_1 = np.sin(z[k]) x_2 = np.cos(z[k]) x_3 = z[k] f = (-1)*np.pi + 0.565*x_1 + 2.674* x_2 + 0.674*x_3 dat=[k+1,round(z[k],3),round(x_1,3),round(x_2,3),round(x_3,3),round(f,3)] # print(dat) dataset.append(dat) step =0.1 weight=[0.2,-0.1,0.1,0.5] print("-------------------------------") print("3.5 Refaça o treinamento com 50 padrões") print("Pesos iniciais:") print(weight) weight_batelada= weight[:] print("Pesos Ajustado:") # test_validacao() print(weight_batelada) test_validacao()
#GUI扩展 from tkinter import * from tkinter import ttk def get_value(key,kw): if key in kw.keys(): return kw[key] else: return None #label控件,宽高单位:像素 class Label_PX(): def __init__(self,root,**kw): self.width = get_value("width",kw) self.height = get_value("height",kw) if self.width is None : self.width=80 if self.height is None : self.height=30 self.frame = Frame(root) self.frame["width"] = self.width self.frame["height"] = self.height self.frame["bg"] = get_value("bg",kw) self.frame.pack_propagate(0) self.label = Label(self.frame) self.label["text"] = get_value("text",kw) self.label["bg"] = get_value("bg",kw) self.label["fg"] = get_value("fg",kw) self.label["font"] = get_value("font",kw) self.label.pack() def place(self,x,y): self.frame.place(x=x,y=y) #text控件,宽高单位:像素 class Text_PX(): def __init__(self,root,**kw): self.width = get_value("width",kw) self.height = get_value("height",kw) if self.width is None : self.width=80 if self.height is None : self.height=30 self.bd = int(get_value("bd",kw)) #根Frame self.r_frame = Frame(root) self.r_frame["width"] = self.width self.r_frame["height"] = self.height self.r_frame["bg"] = get_value("bdcolor",kw) #子Frame self.frame = Frame(self.r_frame) self.frame["width"] = self.width-self.bd*2 self.frame["height"] = self.height-self.bd*2 self.frame["bg"] = get_value("bg",kw) self.frame.place(x=self.bd,y=self.bd) self.frame.pack_propagate(0) self.text = Text(self.frame) self.text["bd"] =0 self.text["relief"] = get_value("relief",kw) self.text["background"] = get_value("background",kw) self.text["width"] = self.width-self.bd*2 self.text["height"] = self.height-self.bd*2 self.text["bg"] = get_value("bg",kw) self.text["fg"] = get_value("fg",kw) self.text["font"] = get_value("font",kw) self.text.pack() def place(self,x,y): self.r_frame.place(x=x,y=y) def insert(self, index, chars, *args): self.text.insert(index, chars, *args) def delete(self, index1, index2=None): self.text.delete(index1, index2) #button控件,宽高单位:像素 class Button_PX(): def __init__(self,root,**kw): self.kw = kw self.width = get_value("width",kw) self.height = get_value("height",kw) self.img_path = get_value("image",kw) self.bd = get_value("bd",kw) if self.img_path is None: self.img = None else: self.img = PhotoImage(file=self.img_path) self.img.width=25 self.img.height=25 if self.width is None : self.width=80 if self.height is None : self.height=25 #根Frame self.r_frame = Frame(root) self.r_frame["width"] = self.width self.r_frame["height"] = self.height self.r_frame["bg"] = get_value("bdcolor",kw) #子Frame self.frame = Frame(self.r_frame) self.frame["width"] = self.width-self.bd*2 self.frame["height"] = self.height-self.bd*2 self.frame["bg"] = get_value("bg",kw) self.frame.place(x=self.bd,y=self.bd) self.frame.pack_propagate(0) self.button = Button(self.frame) self.button["relief"] = get_value("relief",kw) self.button["text"] =get_value("text",kw) self.button["width"] = self.width self.button["height"] = self.height self.button["image"] = self.img self.button["bd"] = 0 self.button["bg"] = get_value("bg",kw) self.button["fg"] = get_value("fg",kw) self.button["font"] = get_value("font",kw) self.button["command"] = get_value("command",kw) self.button["compound"]=get_value("compound",kw) self.button["background"]=get_value("background",kw) self.button["activebackground"]=get_value("activebackground",kw) self.button.bind("<Enter>", self.on_enter) self.button.bind("<Leave>", self.on_leave) self.button.pack() def place(self,x,y): self.r_frame.place(x=x,y=y) def on_enter(self,e): self.button['background'] = get_value("enterBg",self.kw) def on_leave(self,e): self.button['background'] = get_value("leaveBg",self.kw)
import string ALPHABET = string.ascii_uppercase def generate_key(message: str, keyword: str) -> str: key = keyword remain_length = len(message) - len(keyword) for i in range(remain_length): key += key[i] return key def encrypt(message: str, key: str) -> str: result = '' for i, char in enumerate(message): if char not in ALPHABET: result += char continue # index = (ALPHABET.index(char) + ALPHABET.index(key[i])) % len(ALPHABET) # result += ALPHABET[index] result += chr(ord(message[i] + ord(key[i])) % len(ALPHABET) + ord('A')) return result def decrypt(cipher_text: str, key: str) -> str: result = '' for i, char in enumerate(cipher_text): if char not in ALPHABET: result += char continue # index = (ALPHABET.index(char) - ALPHABET.index(key[i]) + len(ALPHABET)) % len(ALPHABET) # result += ALPHABET[index] result = chr((ord(cipher_text[i]) - ord(key[i]) + len(ALPHABET)) % len(ALPHABET) + ord('A')) return result if __name__ == '__main__': t = 'ATTACK ON TITAN' k = generate_key(t, 'CAT') e = encrypt(t, k) print(e) d = decrypt(e, k) print(d)
# 1 def func(number): return number[0] # log n def func2(n): if n <= 1: return else: print(n) func2(n/2) # 0 def func3(numbers): for num in numbers: print(num) # n * log(n) def func4(n): for i in range(int(n)): print(i, end=' ') print() if n <= 1: return func4(n/2) # n ** 2 def func5(numbers): for i in range(len(numbers)): for j in range(len(numbers)): print(numbers[i], numbers[j]) print() # 安定ソート stable sort ソート判定において同一とあると判断された入力データの順序がソート後も変わらない l = [(1, 'Mike'), (5, 'Rina'), (2, 'Bill'), (4, 'emily'), (2, 'June')] def stable(l): l[1], l[2] = l[2], l[1] l[2], l[4] = l[4], l[2] return l l2 = [(1, 'Mike'), (5, 'Rina'), (2, 'Bill'), (4, 'emily'), (2, 'June')] def unstable(l2): l[1], l[4] = l[4], l[1] return l2
import math from random import random, gauss class Attribute: def __init__(self, value, max_value, min_value, mutate_rate=.1, mutate_power=.1, replace_rate=.01): self.value = value self.initial_value = value self.max_value = max_value self.min_value = min_value self.mutate_rate = mutate_rate self.mutate_power = mutate_power self.replace_rate = replace_rate def __float__(self): return self.value def __add__(self, other): return self.value + other def __radd__(self, other): return other + self.value def __sub__(self, other): return self.value - other def __rsub__(self, other): return other - self.value def __abs__(self): return self.value def __mul__(self, other): return self.value * other def __rmul__(self, other): return other * self.value def __str__(self): return str(self.value) def __round__(self, n=None): return self.truncate(n) def truncate(self, decimals=3): """ Returns a value truncated to a specific number of decimal places. """ if not isinstance(decimals, int): raise TypeError("decimal places must be an integer.") elif decimals < 0: raise ValueError("decimal places has to be 0 or more.") elif decimals == 0: return math.trunc(self.value) factor = 10.0 ** decimals return math.trunc(self.value * factor) / factor def clamp(self, value): return max(min(value, self.max_value), self.min_value) def mutate_value(self): r = random() if r < self.mutate_rate: self.value = self.clamp(self.value + gauss(0.0, self.mutate_power)) return self.value if r < self.replace_rate + self.mutate_rate: self.value = self.initial_value return self.value
# In the following exercise you will finish writing smallest_positive which is a function that finds the smallest positive number in a list. def smallest_positive(in_list): x = None for item in in_list: if item <= 0: continue if x == None or item < x: x = item return x # Test cases print(smallest_positive([4, -6, 7, 2, -4, 10])) # Correct output: 2 print(smallest_positive([.2, 5, 3, -.1, 7, 7, 6])) # Correct output: 0.2 print(smallest_positive([-6, -9, -7])) # Correct output: None print(smallest_positive([])) # Correct output: None
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sam Quinn # 11-14-2016 import math def main(): x = 2000000 primes = [] for i in range(0,x): primes.append(i) primes[1] = 0 for i in range(2,int(math.sqrt(x))): if primes[i] != 0: j = i + i while(j < x): primes[j] = 0 j = j + i print "Done finding the 2M primes beginning summing." count = 0 for p in primes: count = count + p print "The sum of every prime under 2M is: %s" % (count) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sam Quinn # 1-29-2017 tri = [] rem = {} def main(): make_tri() #for i in tri: print i tot_sum = best(0,0) print "The best possible path is %s " % tot_sum def best(y,x): global tri global rem # If we have computed this value before return it. if (y,x) in rem: return rem[(y,x)] # We have reached the bottom of the triangle if y == len(tri) -1: return tri[y][x] rem[(y,x)] = tri[y][x] + max(best(y+1,x),best(y+1,x+1)) return rem[(y,x)] def make_tri(): global tri with open('./p067_triangle.txt') as f: for line in f: a = list(map(int,line.split())) tri.append(a) if __name__ == "__main__": main()
from classes import AddressBook def main(): address_book = AddressBook('address_book.csv') print("Address book initialized. Source is:".format(address_book.fp)) while True: command = input("What you want to do? ADD, SHOW, FIND, EXIT") """ Validate input to check that input in these four: ADD, SHOW, FIND, EXIT 1. Exit: close the program 2. Add: add record 3. Show: display records 4. Find: find records """ if command == 'ADD': """ Ask user what type he want to add (org, person) based on this, ask required fields and check field uniqueness if required. After adding record show success message in console """ type_ = input('What type do you want to add? (person, org)') data = {} if type_ == 'person': first_name = input('Enter the first name: ') last_name = input('Enter the last name: ') email = input('Enter the email: ') phone_number = input('Enter the phone number: ') address = input('Enter the address: ') data = {'first_name': first_name, 'last_name': last_name, 'email': email, 'phone_number': phone_number, 'address': address} if type_ == 'org': name = input('Enter the name: ') category = input('Enter the category: ') phone_number = input('Enter the phone number: ') address = input('Enter the address: ') data = {'name': name, 'category': category, 'phone_number': phone_number, 'address': address} address_book.add_record(type_, data) if command == 'SHOW': """ Ask type of records to show: org, person, all print records """ type_ = input('What type of records do you want to see? (org, person, all)') address_book.get_records(type_) if command == 'FIND': """ Ask for type of records to find: org, person, all Ask for string to find any text, at least 5 symbols print results """ type_ = 'all' term = input('What information do you want to see? (at least 5 symbols)') address_book.find_record(type_, term) if command == 'EXIT': raise KeyboardInterrupt if __name__ == '__main__': try: main() except Exception as err: with open('logs.txt', 'a') as f: message = '{} {}:\n {} \n\n'.format( datetime.datetime.now(), err.__class__.__name__, traceback.format_exc() ) f.write(message) print('Error was logged!') except ValueError as vr: print()
''' Created on 2016/11/7 kNN: k Nearest Neighbors Input: inX: vector to compare to existing dataset (1xN) dataSet: size m data set of known vectors (NxM) labels: data set labels (1xM vector) k: number of neighbors to use for comparison (should be an odd number) Output: the most popular class label ''' from numpy import * import operator def createDataSet(): group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]]) labels = ['A','A','B','B'] return group, labels group,labels=createDataSet() print(group) print("~~~~~") #print(labels) #print(random.rand(4,4)) #inx未知类别的值,dotaset已知类别的数据,labels已知相对应的类别,选取与当前点距离最小的k个点 def classify0(inX,dataSet,labels,k): #数组的大小可以通过shape属性获得,这里是二维数组,0轴长度为4 dataSetSize = dataSet.shape[0] #tile()沿inx的各个维度的重复次数,这里获取差值 diffMat = tile(inX,(dataSetSize,1))-dataSet sqDiffMat = diffMat ** 2#获取各行到点的距离 sqDistances = sqDiffMat.sum(axis=1) distances = sqDistances**0.5 #开根号 sortedDistIndicies = distances.argsort() #argsort函数返回的是数组值从小到大的索引值 classCount={} print(distances) print(sortedDistIndicies) print("~~~~~") for i in range(k):#range(k)代表从0到k(不包含k) voteIlabel = labels[sortedDistIndicies[i]] print(voteIlabel) classCount[voteIlabel] = classCount.get(voteIlabel,0)+1 print(classCount.get(voteIlabel,0)) print(classCount) #key参数的值为一个函数,此函数只有一个参数且返回一个值用来进行比较。 #这个技术是快速的因为key指定的函数将准确地对每个元素调用。 sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True) print("~~~~~") print(classCount) print(sortedClassCount) print(sortedClassCount[0][0]) return sortedClassCount[0][0]
from bs4 import BeautifulSoup html = """ <html> <head> <title>BeautifulSoup Example</title> </head> <body> <h1>H1 Tag</h1> <h2>H2 Tag</h2> <p class="A">First P Tag</p> <p class="B">Second P Tag</p> <p id="C"> Third P Tag <p class = "D">Multiple P Tag</p> </p> <p class="A">Fourth P Tag</p> </body> </html> """ print('\n# soup') soup = BeautifulSoup(html, 'html.parser') print(type(soup)) print(soup.prettify()) print('\n# h1\n') h1 = soup.html.body.h1 print(h1) print('\n# p1') p1 = soup.html.body.p print(p1) print(p1.string) print('\n# p2') p2 = p1.next_sibling.next_sibling print(p2) print(list(p2.next_elements)) soup = BeautifulSoup(html, 'html.parser') p3 = soup.find_all("p") # limit=2 print('\n# p3') type((p3)) print(p3) print('\n# link') # class Selector link1 = soup.select_one("p.A") # id Selector link2 = soup.select_one("p#C") print(link1) print(link1.string) print(link2) print(link2.string) print('\n# link2') link1 = soup.select("p.A") print(link1) print(link1[0], link1[1]) print(link1[0].contents)
import random def play(): user = input("\n:::::::::::::::::::::::::\nLet's play a game! \nChoose your weapon: enter 'rock', 'paper', 'scissors' or 'well': ").lower() computer = random.choice(['rock', 'paper', 'scissors', 'well']) print('\n:::::::::::::::::::::::::\nThe computer randomly entered "{}".\n\n⚡⚡⚡⚡⚡⚡⚡⚡\n'.format(computer)) return user, computer #user enters their choice, then the computer enters a random choice def user_win(player, opponent): if player == opponent: return 'Game result: it\'s a tie!\n:::::::::::::::::::::::::\n' elif (player == 'rock' and opponent =='scissors') or (player == 'scissors' and opponent == 'paper') or (player == 'paper' and (opponent == 'rock' or 'well')) or (player == 'well' and (opponent =='scissors' or 'rock')): return 'Game result: you won!\n:::::::::::::::::::::::::\n' elif player not in ['rock', 'paper', 'scissors', 'well']: return 'Oops, enter a correct word.' else: return 'Game result: you lost!\n:::::::::::::::::::::::::\n' def script(): player, opponent = play() print(user_win(player, opponent)) restart = input("Would you like to try again? ") if restart == "yes" or restart == "y": return(script()) if restart == "no" or restart == "n": return("Thank you for playing!") script()
__author__ = 'williamsb' def is_palindrome(number): string = str(number) start = 0 end = len(string) - 1 while string[start] == string[end] and start < end: start += 1 end -= 1 return start > end max_palindrome = 1 for i in range(0, 999): for j in range(0, 999): if is_palindrome(i * j) and max_palindrome < i*j: max_palindrome = i*j print max_palindrome
import time import datetime as dt #-----CALCULATOR-------# #Calculo de minutos entre dos horas formato HH:MM. def dif_min_proy(time_1,time_2): start_dt = dt.datetime.strptime(time_2, '%H:%M') end_dt = dt.datetime.strptime(time_1, '%H:%M') diff = (start_dt - end_dt) minutos= int(diff.seconds/60) print (minutos) return minutos
#FUNCION MODIFICACION ULTIMO PACIENTE INGRESADO def mod_last_dat(lista2,lista): if (lista2 == []): print("No hay pacientes para modificar") else: opc=0 while opc != "s": print("Ingrese una opcion valida") menuPrincipal = menu_mod() opc = opciones() if(opc == "1"): dose=check_input_dose() lis=list(lista2[-1]) lis[0]=dose hour=lis[1] ml=lis[2] listanew=tuple(lis) lista2.pop(-1) lista2.append(listanew) lista.pop(-1) input_data_mod(dose,hour,ml) print ("Regresando al Menu") if(opc == "2"): hour=check_input_hora() lis=list(lista2[-1]) lis[1]=hour dose=lis[0] ml=lis[2] listanew=tuple(lis) lista2.pop(-1) lista2.append(listanew) lista.pop(-1) input_data_mod(dose,hour,ml) print ("Regresando al Menu") if(opc == "3"): ml=check_input_ml() lis=list(lista2[-1]) lis[2]=ml dose=lis[0] hour=lis[1] listanew=tuple(lis) lista2.pop(-1) lista2.append(listanew) lista.pop(-1) input_data_mod(dose,hour,ml) print ("Regresando al Menu")
import sqlite3 class ViewContacts(): """ This class displays all saved members in the treeview and First of all, in order for the members to be displayed regularly, we have to delete them all at once """ def view_command(self): self.tree.delete(*self.tree.get_children()) conn = sqlite3.connect("My_PhoneBook.db") cursor = conn.cursor() cursor.execute("SELECT * FROM member") fetch = cursor.fetchall() for data in fetch: self.tree.insert('', 'end', values=data) cursor.close() conn.close()
""" file: trainMLP.py language: python3 author: [email protected] Rohan Shiroor [email protected] Sandhya Murali This program trains a multi-layer perceptron on training data provided by the user. """ import matplotlib.pyplot import csv import math import random def readFile(file): ''' Reads the train data csv file given as input. Returns the features and classes. :param file: :return: X,Y ''' X = [] Y = [] with open(file,'r') as csvDatafile: csvReader = csv.reader(csvDatafile) for row in csvReader: X.append(row[0:2]) Y.append(row[2:]) return X,Y def init_network(Nin,Nh,Nop): ''' Initializes the multi-layer perceptron with random weights. :param Nin: :param Nh: :param Nop: :return: hiddenWeights, outputWeights ''' hiddenWeights = [[random.uniform(1,-1)for i in range(2)]for i in range(Nh)] outputWeights = [[random.uniform(1,-1)for i in range(5)]for i in range(Nop)] return hiddenWeights,outputWeights def logistic_func_hid(hiddenWeights,X): ''' Calculates the Sigmoid values from the given weights for hidden layer. Input given is X values. :param hiddenWeights: :param X: :return: Sigmoid ''' Sigmoid = [] for j in range(5): z = 1 + hiddenWeights[j][0] * X[0] + hiddenWeights[j][1] * X[1] Sigmoid.append(1.0 / (1.0 + math.exp(-z))) #print(Sigmoid) return Sigmoid def logistic_func_op(outputWeights,Sigmoid,Sig): ''' Calculates the Sigmoid values from the given weights for output layer. Input given is Sigmoid Values for hidden Layer(a values). :param outputWeights: :param Sigmoid: :param Sig: :return:OpSig,Sig ''' OpSig = [] for j in range(4): z = 1 + outputWeights[j][0] * Sigmoid[0] + outputWeights[j][1] * Sigmoid[1]+outputWeights[j][2] * Sigmoid[2]+outputWeights[j][3] * Sigmoid[3]+outputWeights[j][4] * Sigmoid[4] OpSig.append(1.0 / (1.0 + math.exp(-z))) #print(Sigmoid) Sig.append(OpSig) return OpSig,Sig def backprop_Op(OpSig,Y): ''' Calculates the delta values for the output layers and returns it. This is first stage of back propagation. :param Sigmoid: :param OpSig: :param Y: :return: D ''' D = [] for j in range(4): D.append((Y[j] - OpSig[j]) * OpSig[j] * (1 - OpSig[j])) return D def backprop_Hid(D,Sigmoid,outputWeights): ''' Calculates the delta values for the hidden layer and returns it. This is second stage of back propagation. :param D: :param Sigmoid: :param outputWeights: :return: DH ''' DH = [] for j in range(5): D2 = ((D[0]*outputWeights[0][j]+D[1]*outputWeights[1][j]+D[2]*outputWeights[2][j]+D[3]*outputWeights[3][j])*Sigmoid[j]*(1 -Sigmoid[j])) DH.append(D2) return DH def update_weights_hid(X,hiddenWeights,DH): ''' Updates the weights for the connection between the input layer and hidden layer. Third stage of back propagation. :param X: :param hiddenWeights: :param DH: :return:hiddenWeights ''' a = 0.01 for j in range(len(hiddenWeights)): hiddenWeights[j][0] = hiddenWeights[j][0] + (a * DH[j] * X[0]) hiddenWeights[j][1] = hiddenWeights[j][1] + (a * DH[j] * X[1]) return hiddenWeights def update_weights_op(Sigmoid,outputWeights,D): ''' Updates the weights for the connection between hidden layer and output layer. Fourth stage of back propagation. :param Sigmoid: :param outputWeights: :param D: :return: outputWeights ''' a = 0.01 for j in range(len(outputWeights)): outputWeights[j][0] = outputWeights[j][0] + (a * D[j] * Sigmoid[0]) outputWeights[j][1] = outputWeights[j][1] + (a * D[j] * Sigmoid[1]) outputWeights[j][2] = outputWeights[j][2] + (a * D[j] * Sigmoid[2]) outputWeights[j][3] = outputWeights[j][3] + (a * D[j] * Sigmoid[3]) outputWeights[j][4] = outputWeights[j][4] + (a * D[j] * Sigmoid[4]) return outputWeights def calc_SSE(Y,OpSig,err): ''' Calculates the Sum of Squared Error :param Y: :param OpSig: :param err: :return: err ''' val = 0 for i in range(len(Y)): for j in range(4): val+= pow((Y[i][j]-OpSig[i][j]),2) val = val/2 err.append(val) return err def plot_SSE_Epoch(err): ''' Plots the graph of SSE vs Epoch :param err: :return: None ''' plt = matplotlib.pyplot plt.xlabel('Epoch') plt.ylabel('Sum of Squared Errors') plt.title("SSE vs Epoch") epoch = list(range(1,10001)) plt.plot(epoch,err,label='Training Data') plt.show() def main(): ''' The main function of the code. Runs the MLP for 10,000 iterations. Writes the weights for 0,10,100,1000,10000 to respective weights.csv files. :return: None ''' file = input("Enter File Name:") X,Y = readFile(file) ## Convert the list created from csv file into floats ## for i in range(len(X)): X[i][0] = float(X[i][0]) X[i][1] = float(X[i][1]) Y[i][0] = int(Y[i][0]) for i in range(0,len(Y)): if Y[i][0]==1: Y[i]= [1,0,0,0] if Y[i][0]==2: Y[i]= [0,1,0,0] if Y[i][0]==3: Y[i]= [0,0,1,0] if Y[i][0]==4: Y[i]= [0,0,0,1] # Initialize the network with random weights. hiddenWeights, outputWeights = init_network(2,5,4) #print(hiddenWeights) #print(outputWeights) err = [] Sig = [] # Store the randomly initialized weights to weights0.csv file. with open("weights0.csv", "w",newline='') as f: writer = csv.writer(f) writer.writerows(hiddenWeights) writer.writerows(outputWeights) # Runs the MLP for 10,000 Epochs for j in range(10000): # Stochastic Training:- Forward propagation, Back propagation after reading each sample from csv file. for i in range(len(X)): Sigmoid = logistic_func_hid(hiddenWeights, X[i]) # print(Sigmoid) OpSig,Sig = logistic_func_op(outputWeights,Sigmoid,Sig) #print(OpSig) D = backprop_Op(OpSig,Y[i]) # print(D) DH = backprop_Hid(D,Sigmoid,outputWeights) # print(DH) hiddenWeights = update_weights_hid(X[i],hiddenWeights,DH) # print(hiddenWeights) outputWeights = update_weights_op(Sigmoid,outputWeights,D) # print(outputWeights) err = calc_SSE(Y, Sig, err) Sig[:] = [] # Store weights after 10 epochs to weights10.csv file. if j == 9: with open("weights10.csv", "w",newline='') as f: writer = csv.writer(f) writer.writerows(hiddenWeights) writer.writerows(outputWeights) # Store weights after 100 epochs to weights100.csv file. elif j == 99: with open("weights100.csv", "w",newline='') as f: writer = csv.writer(f) writer.writerows(hiddenWeights) writer.writerows(outputWeights) # Store weights after 1000 epochs to weights1000.csv file. elif j == 999: with open("weights1000.csv", "w",newline='') as f: writer = csv.writer(f) writer.writerows(hiddenWeights) writer.writerows(outputWeights) # Store weights after 10,000 epochs to weights10000.csv file. elif j == 9999: with open("weights10000.csv", "w",newline='') as f: writer = csv.writer(f) writer.writerows(hiddenWeights) writer.writerows(outputWeights) #print(hiddenWeights) #print(outputWeights) #print(err) #=print(OpSig) # Plot SSE vs Epoch. plot_SSE_Epoch(err) if __name__ == '__main__': main()
# реализовать функцию my_func(), которая принимает три позиционных аргумента # и возвращает сумму наибольших двух аргументов def chek_num(user_string): """ проверка на ввод чисел(+целые +дробные +отрицательные) """ while True: user_chek = input(user_string) if user_chek.isdigit(): user_chek = int(user_chek) return user_chek try: user_chek = float(user_chek) return user_chek except ValueError: print("\x1b[31m", 'Ошибка! Вводите только числа!', "\x1b[0m") continue def my_func(user_arg1, user_arg2, user_arg3): """ принимает три позиционных аргумента и возвращает сумму наибольших двух аргументов """ my_list = [user_arg1, user_arg2, user_arg3] my_list.sort(reverse=True) return my_list[0] + my_list[1] print(my_func(chek_num("Введите первый аргумент >>> "), chek_num("Введите второй аргумент >>> "), chek_num("Введите третий аргумент >>> ")))
# -*- coding: utf-8 -*- """ This script can be run on any Python intepreter to generate the answers to Q3 in HW2 of ENME 572 Walther Wennholz Johnson - [email protected] """ ## Imports import numpy as np import matplotlib.pyplot as plt ## Given Variables a = [1,10] # convective velocities k = 1 # thermal diffusivity L = 1 # domain length phi_0 = 0 # boundary value at 0 phi_1 = 1 # boundary value at 1 n_nodes_exact = 100 # number of points used to plot the exact solution n_iter = 100 # maximum number of iterations on the entire mesh number_of_nodes = [3,5] # number of nodes the space will be discretized to error_threshold = 0.0001 # error threshold to stop iterating ################### #### FUNCTIONS #### ################### ## define exact solution equations def phi_exact(x, Pe, L): "calculates the exact value of the solution" phi = (np.exp(Pe*(x/L))-1)/(np.exp(Pe)-1) return phi def Peclet(a, L, k): "calculates peclet number" Pe = a*L/k return Pe ## Function to discretize the space def create_mesh(boundary_values, boundary_locations, n_nodes, dimensions): """ takes 1d mesh conditions and returns a vector that only has values where boundary conditions were specified. Row 0 is the coordinates and Row 1 is the array values. Values that have not been initialized are initialized to NaN """ ## create array of invalid values mesh_values = np.full((n_nodes), np.nan) ## create array with correct coordinates mesh_coordinates = np.linspace(*dimensions, n_nodes) ## stack the two arrays mesh = np.stack([mesh_coordinates, mesh_values]) ## find the array index to apply the boundary condition to boundary_indices = np.in1d(mesh[0, :], boundary_locations) ## update the values array with the boundary conditions mesh[1, boundary_indices] = boundary_values return mesh, boundary_indices ## Setting up the basic finite difference functions def phi_CD_only(mesh_values, i, dx, k=1, a=1): """ takes a mesh array and a current index and applies the equation at the current location based on current values using the central difference method for both the convection and diffusion. Operates in-place """ ## get the function values around the node of interest phi = mesh_values[i-1:i+2] ## if a node is NaN, replace it with 0. Better strategies could be devised ## for this step, but this naive approach is enough in this case phi[np.isnan(phi)]=0 ## calculate the values of each of the terms that affect the current index, ## and then add them up term_1 = phi[0]*(a*dx + 2*k) term_2 = phi[2]*(2*k-a*dx) phi[1] = (term_1 + term_2)/(4*k) return None def phi_CD_and_FD(mesh_values, i, dx, k=1, a=1): """ takes a mesh array and a current index and applies the equation at the current location based on current values using the central difference method for diffusion, and forward difference for convection. Operates in-place """ ## get the function values around the node of interest phi = mesh_values[i-1:i+2] ## initial values guess initial = np.linspace(0,1, len(mesh_values)) phi_initial = initial[i-1:i+2] ## if a node is NaN, replace it with 0. Better strategies could be devised ## for this step, but this naive approach is enough in this case phi[np.isnan(phi)]=phi_initial[np.isnan(phi)] ## calculate the values of each of the terms that affect the current index, ## and then add them up term_1 = phi[0]*(k) term_2 = phi[2]*(k-a*dx) phi[1] = (term_1 + term_2)/(2*k-a*dx) return None def phi_CD_and_BD(mesh_values, i, dx, k=1, a=1): """ takes a mesh array and a current index and applies the equation at the current location based on current values using the central difference method for diffusion, and forward difference for convection. Operates in-place """ ## get the function values around the node of interest phi = mesh_values[i-1:i+2] ## if a node is NaN, replace it with 0. Better strategies could be devised ## for this step, but this naive approach is enough in this case phi[np.isnan(phi)]=0 ## calculate the values of each of the terms that affect the current index, ## and then add them up term_1 = phi[0]*(k+a*dx) term_2 = phi[2]*(k) phi[1] = (term_1 + term_2)/(2*k+a*dx) return None def find_dx(mesh_coordinates, i): """ takes a mesh array and a current index and finds the average delta x around that index. It finds the exact dx for a uniform node distribution but also handles the case where there are small variations around a node of a uniform mesh """ ## get differential of coordinates around node dx_array = np.diff(mesh_coordinates[i-1:i+2]) ## get average delta dx = dx_array.mean() return dx def array_iteration(fun, mesh, fixed_index, kappa, a): """ takes a function and a mesh, and iterates through the mesh values with the function """ ## iterates through every node in the mesh coordinates ## updating the entire mesh for i, coordinate in enumerate(mesh[0]): ## check if the location isn't a boundary condition ## and if it is not find the delta x around that node, and then ## update that node based on the chosen finite difference function if not(fixed_index[i]): #print(i) dx = find_dx(mesh[0], i) fun(mesh[1], i, dx, kappa, a) ############################# #### CALCULATE SOLUTIONS #### ############################# ## Create a for loop to create all necessary graphs ## iterate through convective velocities for velocity in a: #[1,10] ## iterate through all possible numbers of nodes finite difference for n_nodes in number_of_nodes: #[3,5] ##iterate each of the schemes for scheme in [phi_CD_only, phi_CD_and_BD]: ## create the mesh to iterate through and store the indices of the ## boundary conditions mesh, boundary_indices = create_mesh(boundary_values = [phi_0, phi_1], boundary_locations = [0,L], n_nodes = n_nodes, dimensions = [0, L]) ## start an array to store the delta between each solution error_array = [np.inf, np.inf] ## apply the scheme iteratively until the change between the ## previous and the next itireation is below the threshold, or ## until we get to the maximum allowed number of iterations, ## when the program prints it failed to converge on a solution. while error_array[-1]>=error_threshold or len(error_array)<5: ## store previous iteration of the mesh to calculate error prev_mesh_iter = mesh[1].copy() ## applies the scheme to the mesh once array_iteration(scheme, mesh, boundary_indices, kappa = k, a = velocity) ## appends the average numberical change between ## the last two iterations error_array.append(np.abs((mesh[1]-prev_mesh_iter)).mean()) ## if exceeding the max number of iterations, end iterations if len(error_array)>=n_iter: print(f"v={velocity}, n_nodes={{n_nodes}}, scheme {scheme.__name__} failed to converge") break ## create data for plotting exact solution x_exact_plot = np.linspace(0,1,n_nodes_exact) Pe_plot = Peclet(velocity, L, k) phi_ex_plot = phi_exact(x_exact_plot, Pe_plot, L) ## plot the finite difference solution plt.plot(mesh[0], mesh[1]) ## plot the exact solution on the same graph plt.plot(x_exact_plot, phi_ex_plot) ## add a legend plt.legend(["finite difference", "exact"]) ## add a title plt.title(f"velocity = {velocity} , number of nodes = {n_nodes}" f"\n with function {scheme.__name__}" f"\n n_iter = {len(error_array)-2} for delta in solution = {error_array[-1]:.3e}") plt.ylabel('phi') plt.tight_layout() plt.xlabel('x coordinate') plt.savefig(f"{scheme.__name__} velocity = {velocity} n_nodes = {n_nodes}") ## force multiple graphs to be created plt.pause(0.001)
#!/bin/python3 import math import os import random import re import sys from collections import defaultdict # Complete the makingAnagrams function below. def makingAnagrams(s1, s2): d = defaultdict(int) for i in s1: d[i] += 1 #print(d[i]) for i in s2: d[i] -= 1 count = 0 for i in d: count += abs(d[i]) #print(d[i]) return(count) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s1 = input() s2 = input() result = makingAnagrams(s1, s2) fptr.write(str(result) + '\n') fptr.close()
def mergesort(arr): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] mergesort(L) mergesort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 def readfile(file): with open(file) as f: array = [[int(x) for x in line.split()] for line in f] return array def writefile(file, array): with open(file, 'w') as f: f.write('\n'.join([' '.join(map(str, arr)) for arr in array])) f.write('\n') if __name__ == '__main__': array = readfile('data.txt') for arr in array: mergesort(arr) writefile('merge.txt', array)
def Knapsack(price, weights, cap): n = len(price) r = [[0 for _ in range(cap + 1)] for _ in range(n + 1)] # Build table r[][] in bottom up manner for i in range(n + 1): for j in range(cap + 1): if i == 0 or j == 0: r[i][j] = 0 elif weights[i - 1] <= j: r[i][j] = max(price[i - 1] + r[i - 1][j - weights[i - 1]], r[i - 1][j]) else: r[i][j] = r[i - 1][j] # Stores the result of Knapsack res = r[n][cap] items = [] # list to store the items w = cap for i in range(n, 0, -1): if res <= 0: break # Either the result comes from the top (K[i-1][w]) or # from (val[i-1] + K[i-1] [w-wt[i-1]]) as in Knapsack # table. If it comes from the latter one, it means the # item is included. if res == r[i - 1][w]: continue else: items.insert(0, i) res -= price[i - 1] w -= weights[i - 1] return items, r[n][cap] def readfile(file): with open(file) as f: T = int(next(f)) testcases = [] for i in range(T): N = int(next(f)) price = [] weights = [] for _ in range(N): p, w = [int(x) for x in next(f).split()] price.append(p) weights.append(w) F = int(next(f)) family = [] for _ in range(F): family.append(int(next(f))) testcases.append([price, weights, family]) return testcases def solve(testcases): output = [] for t in testcases: sum = 0 family = [] for cap in t[2]: items, res = Knapsack(t[0], t[1], cap) sum += res family.append(items) output.append([sum, family]) return output def writefile(file, output): with open(file, 'w') as f: for i in range(len(output)): f.write('Test Case %s\n' % str(i+1)) f.write('Total Price %s\n' % str(output[i][0])) f.write('Member Items:\n') for j in range(len(output[i][1])): f.write('%s: ' % str(j+1)) f.write(' '.join(map(str, output[i][1][j]))) f.write('\n') f.write('\n') if __name__ == '__main__': testcases = readfile('shopping.txt') output = solve(testcases) writefile('results.txt', output)
import builtins INP = object() # object to recognize inputs class t(str): def __add__(self, other: object): if isinstance(other, str) or other is INP: return ColorChain([self, other]) elif isinstance(other, ColorChain): return ColorChain([self, *other]) else: raise NotImplementedError class ColorChain(tuple): _print = print def __enter__(self): builtins.print = self def __exit__(self, *stuff): builtins.print = self._print def __add__(self, other: object): if isinstance(other, str) or other is INP: return ColorChain([*self, other]) elif isinstance(other, ColorChain): return ColorChain([*self, *other]) else: raise NotImplementedError def __repr__(self): if not self.count(INP): return self(write=False) return repr(super()) def __call__(self, *text, write: bool = True): requires = self.count(INP) if requires > len(text): raise ValueError("Not enough input for chain. Provided {}, requires {}".format(len(text), requires)) sentence = "" text = list(text) for item in self: if item is INP: sentence += text.pop(0) else: sentence += item if write: self._print(sentence) else: return sentence
import math import copy import random from Program.ball import Ball from Program.helpers.constants import Constants from Program.space import Space ''' - - - | 0 | 1 | 2 | 3 | 4 | 5 | 6 | - - - | 7 | 8 | 9 | 10 | 11 | 12 | 13 | - - - | 14 | 15 | 16 | 17 | 18 | 19 | 20 | - - - | 21 | 22 | 23 | 24 | 25 | 26 | 27 | - - - | 28 | 29 | 30 | 31 | 32 | 33 | 34 | - - - | 35 | 36 | 37 | 38 | 89 | 40 | 41 | - - - | 42 | 43 | 44 | 45 | 46 | 47 | 48 | ''' class Board: def __init__(self): self.balls = [] self.final_balls = [] self.board = [Space()] * 25 # 25, 49, 121, 168 self.row_length = int(math.sqrt(len(self.board))) self.extra = self.row_length/2 + 1 print("Extra is :", int(self.extra), "row length: ", self.row_length, "board length: ", len(self.board)) # make board with balls self.create_legal_valid_board() """"Move balls in game, move is tuple like: move = (index, direction, single or double), index = 1..48, direction =[up, right, down, left], single/double = 1/2""" def move_neighbor_balls(self, move, board): neighbor_index = self.get_neighbors_in_desired_direction(move) # raw_of_current_ball_to_move = self.get_current_column(move[0]) last_neighbor_index = 0 while True: # while there is a neighbor in the desired direction if neighbor_index == last_neighbor_index: break if neighbor_index > len(board) - 1 or neighbor_index < 0: break neighbor_move = (neighbor_index, move[1]) last_neighbor_index = neighbor_index self.move_ball_to_empty(neighbor_move, board) neighbor_index = self.get_neighbors_in_desired_direction(neighbor_move) # print(neighbor_move) """ Used to get all index of neighbors in the direction specified by the move "move = (index, direction)". """ def get_neighbors_in_desired_direction(self, move): index = move[0] raw_of_current_ball_to_move = self.get_current_column(move[0]) if move[1] == 0: index = move[0] + self.row_length elif move[1] == 1: # right index_before = move[0] - 1 if index_before in raw_of_current_ball_to_move : index = move[0] - 1 elif move[1] == 2: # down index = move[0] - self.row_length elif move[1] == 3: # left index_before = move[0] + 1 if index_before in raw_of_current_ball_to_move: index = index_before return index """ Given a index it returns a list of the neighbors in the same column. """ def get_current_column(self, position): list_index_of_raw = [] i = 1 while True and (position + i) < len(self.board): # to the right of index if ((position + i) % self.row_length) == 0: break list_index_of_raw.append(position + i) i += 1 i = 1 while True and (position - i) > 0: # to the left of index list_index_of_raw.append(position-i) if (position - i) % self.row_length == 0: break i += 1 list_index_of_raw.append(position) return list_index_of_raw """ Given an index and direction, this method moves the object in the index to the furthest empty space in the desires direction. """ def move_ball_to_empty(self, move, board): # move any ball in a desired direction to empty space new_index = self.get_index_in_direction(move, board) if new_index != move[0]: board[new_index] = board[move[0]] board[move[0]] = Space() """ Gives index of the further empty space in the direction specified in the move. """ def get_index_in_direction(self, move, board): index = move[0] raw_of_current_ball_to_move = self.get_current_column(move[0]) # list of indices in the same column. if move[1] == 0: # up x = 1 while True: if move[0]-self.row_length*x >= 0 and board[move[0]-self.row_length*x].color == Constants.EMPTY: index = move[0] - self.row_length*x x += 1 else: break elif move[1] == 1: # right x = 1 while True: if move[0] + x < len(board) and board[move[0] + x].color == Constants.EMPTY: sure = move[0] + x if sure in raw_of_current_ball_to_move: index = sure x += 1 else: break elif move[1] == 2: # down x = 1 while True: if move[0] + self.row_length*x < len(board) and board[move[0] + self.row_length*x].color == Constants.EMPTY: index = move[0] + self.row_length*x x += 1 else: break elif move[1] == 3: # left x = 1 while True: if move[0] - x >= 0 and board[move[0] - x].color == Constants.EMPTY: sure = move[0] - x if sure in raw_of_current_ball_to_move: index = sure x += 1 else: break return index """ Before doing a move with method do_move(), the move is first checked here. The method return True if the move is in a list valid moves and False otherwise. This method uses the board of this class ( self.board) to find the valid moves. """ def check_before_do_move(self, *args): if len(args) == 1: move = (args[0][0], args[0][1], 1) else: move = [(args[0][0], args[0][1], 1), (args[1][0], args[1][1], 2)] single, double = self.check_if_valid_move(self.board) if len(args) == 1: if move in single: return True elif len(args) == 2: if move in double: return True return False """ This method is used by the class Collecto to make changes in the board given one or two moves. """ def do_move(self, *args): if len(args) == 1: move = (args[0][0], args[0][1], 1) else: move = [(args[0][0], args[0][1], 1), (args[1][0], args[1][1], 2)] move2 = (args[1][0], args[1][1], 2) # get list of single and double moves single, double = self.check_if_valid_move(self.board) # print("\n", "single: ", single, "double: ", double, "move :", move) # check if move is in single move list or in double mov list or if the list are empty # if move is single move if len(args) == 1: if move in single: self.move_ball_to_empty(move, self.board) # first move the desired ball self.move_neighbor_balls(move, self.board) # move the neighbors # get index of balls with adjacent balls # put the balls in a list # elif double move is the list of double move elif len(args) == 2: if move in double: # do first move self.move_ball_to_empty(move[0], self.board) self.move_neighbor_balls(move[0], self.board) # do second move self.move_ball_to_empty(move[1], self.board) self.move_neighbor_balls(move[1], self.board) # put the balls in a list and change the object from ball to space """ This method is used to check a move before it is made, this method is almost the same as, check before do move(), the difference is that this method can be outside this class, a move and a board s given as arguments, which means this method does not use the board of this class.""" def check_before_do_move_outside(self, *args, board): if len(args) == 1: move = (args[0][0], args[0][1], 1) else: move = [(args[0][0], args[0][1], 1), (args[1][0], args[1][1], 2)] single, double = self.check_if_valid_move(board) if len(args) == 1: if move in single: return True elif len(args) == 2: if move in double: return True return False """ Similar with do_move(), makes a move but it is given a board as argument, this board can be specdified outside this class, but the advantage is that it uses some of the methods defined here.""" def do_move_outside(self, *args, board): if len(args) == 1: move = (args[0][0], args[0][1], 1) else: move = [(args[0][0], args[0][1], 1), (args[1][0], args[1][1], 2)] move2 = (args[1][0], args[1][1], 2) # get list of single and double moves single, double = self.check_if_valid_move(board) # print("\n", "single: ", single, "double: ", double, "move :", move) # check if move is in single move list or in double mov list or if the list are empty # if move is single move if len(args) == 1: if move in single: self.move_ball_to_empty(move, board) # first move the desired ball self.move_neighbor_balls(move, board) # move the neighbors # get index of balls with adjacent balls # put the balls in a list # elif double move is the list of double move elif len(args) == 2: if move in double: # do first move self.move_ball_to_empty(move[0], board) self.move_neighbor_balls(move[0], board) # do second move self.move_ball_to_empty(move[1], board) self.move_neighbor_balls(move[1], board) # put the balls in a list and change the object from ball to space """ This method returns a list of balls that have neighbors with similar color, this checks the boad: self.board. """ def get_adjacent_balls(self): list_of_balls = [] indexes = [] for i, ball_or_space in enumerate(self.board): move = (i, None) if self.check_if_ball_has_adjacents(move, self.board): list_of_balls.append(ball_or_space) indexes.append(i) for i in indexes: self.board[i] = Space() return list_of_balls """ This method returns a list of balls that have neighbors with similar color, this checks a board given as argument then this method can be used outside this class. """ def get_adjacent_balls_outside(self, board): list_of_balls = [] indexes = [] for i, ball_or_space in enumerate(board): move = (i, None) if self.check_if_ball_has_adjacents(move, board): list_of_balls.append(ball_or_space) indexes.append(i) for i in indexes: board[i] = Space() return list_of_balls def do_move_inside(self, move, board): self.move_ball_to_empty(move, board) # first move the desired ball self.move_neighbor_balls(move, board) # move the neighbors """ Returns a list with valid moves given a board of type list. """ def check_if_valid_move(self, board): # make a list for single and double single_moves = [] double_moves = [] moves = self.get_possible_moves(board) for i, move in enumerate(moves): board_copy1 = self.copy_of_board(board) self.do_move_inside(move, board_copy1) if self.check_if_board_has_adjacents(board_copy1): new_move = (move[0], move[1], Constants.SINGLE) single_moves.append(new_move) moves2 = self.get_possible_moves(board_copy1) for move2 in moves2: board_copy2 = self.copy_of_board(board_copy1) self.do_move_inside(move2, board_copy2) # index = (self.get_index_in_direction(move2, board_copy2), board_copy2) #if move != move2: # if self.check_if_ball_has_adjacents(index, board_copy2): if self.check_if_board_has_adjacents(board_copy2): new_move = [(move[0], move[1], Constants.SINGLE), (move2[0], move2[1], Constants.DOUBLE)] double_moves.append(new_move) #elif move == move2: # print("Never really expected first ") # pass elif not self.check_if_board_has_adjacents(board_copy1): moves2 = self.get_possible_moves(board_copy1) for move2 in moves2: board_copy2 = self.copy_of_board(board_copy1) self.do_move_inside(move2, board_copy2) # index = (self.get_index_in_direction(move2, board_copy2), board_copy2) # if self.check_if_ball_has_adjacents(index, board_copy2): if self.check_if_board_has_adjacents(board_copy2): new_move = [(move[0], move[1], Constants.SINGLE), (move2[0], move2[1], Constants.DOUBLE)] double_moves.append(new_move) return single_moves, double_moves """ Given a move and a board it checks if the board has balls with similar color. """ def check_if_ball_has_adjacents(self, move, board): # check if the ball with the index and its surroundings are the same # if move[1] == 0: # up raw_of_current_ball_to_move = self.get_current_column(move[0]) if isinstance(board[move[0]], Ball): if move[0] - self.row_length >= 0 and board[move[0] - self.row_length].color == board[move[0]].color: return True # elif move[1] == 1: # right elif move[0] + 1 < len(board) and board[move[0] + 1].color == board[move[0]].color: index = move[0] + 1 if index in raw_of_current_ball_to_move: return True # elif move[1] == 2: # down elif move[0] + self.row_length < len(board) and board[move[0] + self.row_length].color == board[move[0]].color: return True # elif move[1] == 3: # left elif move[0] - 1 >= 0 and board[move[0] - 1].color == board[move[0]].color: index = move[0] - 1 if index in raw_of_current_ball_to_move: return True # check is ball is in list of balls # return true if a similar ball is found in a specified direction # otherwise return False return False """ Checks if a board given as argument has balls with similar neighbors. Returns True is there are and False otherwise. """ def check_if_board_has_adjacents(self, board): for i, ball_or_space in enumerate(board): move = (i, None) if self.check_if_ball_has_adjacents(move, board): return True return False def get_possible_moves(self, board): # make a tuple list for moves moves = [] # check if each ball has balls in the surroundings index = 0 for ball_or_space in board: if not isinstance(ball_or_space, Space): directions = Constants.DIRECTIONS for direction in directions: if direction == 0: # check up if index - self.row_length >= 0 and board[index - self.row_length].color == Constants.EMPTY: move = (index, direction) moves.append(move) elif direction == 1: # check right if index + 1 < len(board) and board[index + 1].color == Constants.EMPTY: move = (index, direction) moves.append(move) elif direction == 2: # check down if index + self.row_length < len(board) and board[index + self.row_length].color == Constants.EMPTY: move = (index, direction) moves.append(move) elif direction == 3: # check left if index - 1 >= 0 and board[index - 1].color == Constants.EMPTY: move = (index, direction) moves.append(move) index += 1 return moves """ Returns true is there there is not emtpy spaces in the board. """ # TODO check is method is neccesary. def checks_if_board_empty(self): for ball_or_space in self.board: if ball_or_space == Space(): return False return True """ return true there are move possible using the board: self.board """ def check_if_any_moves_possible(self): single, double = self.check_if_valid_move(self.board) if not single and not double: return False return True """ This method checks is there are moves available in a board given as argument. """ def check_if_any_moves_possible_ouside(self, board): single, double = self.check_if_valid_move(board) if not (single and double): return False return True """ Checks if the given index is inside the board. """ def check_index_in_board(self, index): if index > len(self.board) or index < len(self.board): return False return True """ Makes a list of balls with 6 different colors. """ def make_balls(self): for i in range(0, int((len(self.board) - 1) / 6)): # self.row_length + 1 for color in Constants.COLORS: self.balls.append(Ball(color)) """ This method populates a board of type list. """ def create_board(self): self.board = [Space()] * self.row_length*self.row_length self.balls.clear() self.make_balls() random.shuffle(self.balls) for i in range(0, len(self.board)): counter = 0 while True: try: if self.balls[counter].color != self.board[i - 1].color and self.balls[counter].color != self.board[i - self.row_length].color: break elif self.balls[counter].color != self.board[i - 1].color and i > self.row_length*self.row_length - self.extra: break except IndexError as i: z = i break counter += 1 if self.balls: try: ball = self.balls.pop(counter) except IndexError as e: ball = self.balls.pop(counter-1) i = len(self.board)-2 self.final_balls.append(ball) if i != (self.row_length*self.row_length - 1)/2: self.board[i] = ball elif i == (self.row_length*self.row_length - 1)/2: self.board[len(self.board)-1] = ball """ This method makes a valid board at the beginning of the game. """ def create_legal_valid_board(self): counter = 0 while not self.check_valid_board(): self.create_board() counter += 1 print(counter) if counter > 100: break """ Check is the initial board has not neighbors with the same color. This is one of the rules of the game. """ def check_valid_board(self): board = self.board for i in range(0, len(self.board)): try: if board[i] == board[i + 1]: return False elif board[i] == board[i - 1]: return False elif board[i] == board[i + self.row_length]: return False elif board[i] == board[i - 1]: return False except IndexError as e: z = e return True def get_board(self): return self.board """ This method is to make a string representation of the board. The method is used outside this class. """ def board_to_string(self): field = self.get_board() print("\n---------------------------") for i in range(0, len(field)): if i % self.row_length == 0: print(" ") if self.board[i].color == " ": print("|" + " " + "|", end='') else: print("|" + field[i].color + "|", end='') print("\n") """ Method to make a string representation of the board. This method can be used internally. """ def board_to_string_inside(self, board): field = board print("\n---------------------------") for i in range(0, len(field)): if i % self.row_length == 0: print(" ") if board[i].color == " ": print("|" + " " + "|", end='') else: print("|" + field[i].color + "|", end='') print("\n") """ Check is the board is empty. """ def board_empty(self): for i in range(0, len(self.board)): if self.board[i] != " ": return False return True """ Makes a copy the the board of type list. Given as argument a board. """ def copy_of_board(self, board): return copy.copy(board) """ Makes a coy of the the class. """ def deep_copy(self): return copy.deepcopy(self) """ board = Board() board.board_to_string() """
from typing import List from testcase import testcase class Solution: def numUniqueEmails(self, emails: List[str]) -> int: uniq = set() for email in emails: uniq.add(self.process(email)) return len(uniq) def process(self, email: str) -> str: localname, domain = email.lower().split("@") localname = localname.split("+")[0].replace(".", "") return "@".join((localname, domain)) def test(): s = Solution() for t, expected in testcase: assert s.numUniqueEmails(t) == expected if __name__ == "__main__": s = Solution()
from testcase import testcase class Solution: def reverseBits(self, n: int) -> int: as_bin = bin(n)[2:] as_bin = "0" * (32 - len(as_bin)) + as_bin return int(as_bin[::-1], 2) def test(): s = Solution() for t, expected in testcase: assert s.reverseBits(t) == expected if __name__ == "__main__": s = Solution()
from itertools import combinations from typing import List from testcase import testcase class Solution: def totalHammingDistance(self, nums: List[int]) -> int: if not nums: return 0 bins = [str(bin(n))[:1:-1] for n in nums] longest = max(bins, key=len) longest_len = len(longest) for i, _ in enumerate(bins): bins[i] += "0" * (longest_len - len(bins[i])) bins[i] = [int(s) for s in list(bins[i])] return sum( self.hammingDistance(a, b) for a, b in combinations(bins, 2) ) def hammingDistance(self, bx: List[int], by: List[int]) -> int: count = 0 for a, b in zip(bx, by): if a != b: count += 1 return count def test(): s = Solution() for t, expected in testcase: assert s.totalHammingDistance(t) == expected if __name__ == "__main__": s = Solution() for t, _ in testcase: print(len(t)) print(len(set(t))) print(s.totalHammingDistance(t))
from testcase import testcase class Solution: def isPowerOfFour(self, num: int) -> bool: if num == 1: return True num /= 4 if num < 1: return False return self.isPowerOfFour(num) def test(): s = Solution() for t, expected in testcase: assert s.isPowerOfFour(t) == expected if __name__ == "__main__": s = Solution()
from operator import mul from functools import reduce from testcase import testcase class Solution: def subtractProductAndSum(self, n: int) -> int: sequence = [int(s) for s in str(n)] return self.product(sequence) - self.sum(sequence) def product(self, s) -> int: return reduce(mul, s) def sum(self, s) -> int: return sum(s) def test(): s = Solution() for t, expected in testcase: assert s.subtractProductAndSum(t) == expected if __name__ == "__main__": s = Solution() for t, _ in testcase: print(s.subtractProductAndSum(t))
#!/usr/bin/env python3 """ Decoders for binary representations. """ from toolz.itertoolz import pluck import numpy as np from .. decoder import Decoder ############################## # Class BinaryToIntDecoder ############################## class BinaryToIntDecoder(Decoder): """A decoder that converts a Boolean-vector genome into an integer-vector phenome. """ def __init__(self, *descriptors): """Constructs a decoder that will convert a binary representation into a corresponding int-value vector. :param descriptors: is a test_sequence of integer that determine how the binary test_sequence is to be broken up into chunks for interpretation :return: a function for real-value phenome decoding of a test_sequence of binary digits The `segments` parameter indicates the number of (genome) bits per ( phenome) dimension. For example, if we construct the decoder >>> d = BinaryToIntDecoder(4, 3) then it will look for a genome of length 7, with the first 4 bits mapped to the first phenotypic value, and the last 3 bits making up the second: >>> import numpy as np >>> d.decode(np.array([0,0,0,0,1,1,1])) array([0, 7]) """ super().__init__() self.descriptors = descriptors self.powers_2 = None def decode(self, genome, *args, **kwargs): """ Converts a Boolean genome to an integer-vector phenome by interpreting each segment of the genome as low-endian binary number. :param genome: a list of 0s and 1s representing a Boolean genome :return: a corresponding list of ints representing the integer-vector phenome For example, a Boolean representation of [1, 12, 5] can be decoded like this: >>> import numpy as np >>> d = BinaryToIntDecoder(4, 4, 4) >>> b = np.array([0,0,0,1, 1, 1, 0, 0, 0, 1, 1, 0]) >>> d.decode(b) array([ 1, 12, 6]) """ if not isinstance(genome, np.ndarray): raise ValueError(("Expected genome to be a numpy array. " f"Got {type(genome)}.")) values = np.zeros(len(self.descriptors), dtype=int) offset = 0 # how far are we into the binary test_sequence for i, descriptor in enumerate(self.descriptors): # snip out the next test_sequence cur_sequence = genome[offset:offset + descriptor] if self.powers_2 is None or cur_sequence.size > self.powers_2.size: self.powers_2 = 1 << np.arange(cur_sequence.size)[::-1] values[i] = BinaryToIntDecoder.__binary_to_int( cur_sequence, powers_2=self.powers_2) offset += descriptor return values @staticmethod def __binary_to_int(b, powers_2=None): """Convert the given binary string to the equivalent >>> import numpy as np >>> b = np.array([0, 1, 0, 1]) >>> BinaryToIntDecoder._BinaryToIntDecoder__binary_to_int(b) 5 """ # compute powers of 2 and cache results if powers_2 is None or b.size > powers_2.size: powers_2 = 1 << np.arange(b.size)[::-1] # dot product of bit vector with powers of 2 return b.dot(powers_2[-b.size:]) @staticmethod def __binary_to_str(b): """Convert a vector of binary values into a simple string of binary. For example, >>> import numpy as np >>> b = np.array([0, 1, 0, 1]) >>> BinaryToIntDecoder._BinaryToIntDecoder__binary_to_str(b) '0101' """ return "".join([str(x) for x in b]) ############################## # Class BinaryToRealDecoderCommon ############################## class BinaryToRealDecoderCommon(Decoder): """ Common implementation for binary to real decoders. The base classes BinaryToRealDecoder and BinaryToRealGreyDecoder differ by just the underlying binary to integer decoder. Most all the rest of the binary integer to real-value decoding is the same, hence this class. """ def __init__(self, *segments): """ :param segments: is a test_sequence of tuples of the form (number of bits, minimum, maximum) values :return: a function for real-value phenome decoding of a test_sequence of binary digits """ super().__init__() # Verify that segments have the correct dimensionality for i, seg in enumerate(segments): if len(seg) != 3: raise ValueError("Each segment must be a have exactly three " "elements (num_bits, min, max), " + f"but segment {i} is '{seg}'.'") # first we want to create an _int_ encoder since we'll be using that # to do the first pass # snip out just the binary segment lengths from the set of tuples; # we save this for the subclasses for their binary to integer decoders self.len_segments = np.array(list(pluck(0, segments))) # how many possible values per segment # cardinalities = [2 ** i for i in self.len_segments] cardinalities = 1 << self.len_segments # We will use this function to first decode to integers. # This is assigned in the sub-classes depending on whether we want to # use grey encoding or not to convert from binary to integer sequences. self.binary_to_int_decoder = None # Now get the corresponding real value ranges self.lower_bounds = np.array(list(pluck(1, segments))) self.upper_bounds = np.array(list(pluck(2, segments))) # This corresponds to the amount each binary value is multiplied by # to get the final real value (plus the lower bound offset, of course) self.increments = \ (self.upper_bounds - self.lower_bounds) / (cardinalities - 1) def decode(self, genome, *args, **kwargs): """Convert a list of binary values into a real-valued vector.""" int_values = self.binary_to_int_decoder.decode(genome) values = self.lower_bounds + (int_values * self.increments) return values ############################## # Class BinaryToRealDecoder ############################## class BinaryToRealDecoder(BinaryToRealDecoderCommon): def __init__(self, *segments): """ This returns a function that will convert a binary representation into a corresponding real-value vector. The segments are a collection of tuples that indicate how many bits per segment, and the corresponding real-value bounds for that segment. :param segments: is a test_sequence of tuples of the form (number of bits, minimum, maximum) values :return: a function for real-value phenome decoding of a test_sequence of binary digits For example, if we construct the decoder then it will look for a genome of length 8, with the first 4 bits mapped to the first phenotypic value, and the last 4 bits making up the second. The traits have a minimum value of -5.12 (corresponding to 0000) and a maximum of 5.12 (corresponding to 1111): >>> import numpy as np >>> d = BinaryToRealDecoder((4, -5.12, 5.12),(4, -5.12, 5.12)) >>> d.decode(np.array([0, 0, 0, 0, 1, 1, 1, 1])) array([-5.12, 5.12]) """ super().__init__(*segments) # We will use this function to first decode to integers self.binary_to_int_decoder = BinaryToIntDecoder(*self.len_segments) ############################## # Class BinaryToIntGreyDecoder ############################## class BinaryToIntGreyDecoder(BinaryToIntDecoder): """ This performs Gray encoding when converting from binary strings. See also: https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code For example, a grey encoded Boolean representation of [1, 8, 4] can be decoded like this: >>> import numpy as np >>> d = BinaryToIntGreyDecoder(4, 4, 4) >>> b = np.array([0,0,0,1, 1, 1, 0, 0, 0, 1, 1, 0]) >>> d.decode(b) array([1, 8, 4]) """ def __init__(self, *descriptors): super().__init__(*descriptors) @staticmethod def __gray_encode(num): """ https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code :param value: integer value to be gray encoded :return: gray encoded integer """ mask = num >> 1 while mask != 0: num = num ^ mask mask = mask >> 1 return num def decode(self, genome, *args, **kwargs): # First decode the integers from the binary representation using # regular binary decoding. values = super().decode(genome) # TODO: find a way to vectorize using numpy ops gray_encoded_values = [BinaryToIntGreyDecoder.__gray_encode(v) for v in values] return np.array(gray_encoded_values) ############################## # Class BinaryToRealGreyDecoder ############################## class BinaryToRealGreyDecoder(BinaryToRealDecoderCommon): def __init__(self, *segments): """ This returns a function that will convert a binary representation into a corresponding real-value vector. The segments are a collection of tuples that indicate how many bits per segment, and the corresponding real-value bounds for that segment. :param segments: is a test_sequence of tuples of the form (number of bits, minimum, maximum) values :return: a function for real-value phenome decoding of a test_sequence of binary digits For example, if we construct the decoder then it will look for a genome of length 8, with the first 4 bits mapped to the first phenotypic value, and the last 4 bits making up the second. The traits have a minimum value of -5.12 (corresponding to 0000) and a maximum of 5.12 (corresponding to 1111): >>> import numpy as np >>> d = BinaryToRealGreyDecoder((4, -5.12, 5.12),(4, -5.12, 5.12)) >>> d.decode(np.array([0, 0, 0, 0, 1, 1, 1, 1])) array([-5.12 , 1.70666667]) """ super().__init__(*segments) # We will use this function to first decode to integers self.binary_to_int_decoder = BinaryToIntGreyDecoder(*self.len_segments) if __name__ == '__main__': pass
import pygame from pygame.sprite import Sprite class Asteroid(Sprite): """space rock!""" def __init__(self, ai_settings, screen): super(Asteroid, self).__init__() self.ai_settings = ai_settings self.screen = screen self.speed_factor = self.ai_settings.asteroid_speed_factor # Load the asteroid image and set its Rect attributes self.image = pygame.image.load('images/asteroid.bmp') self.rect = self.image.get_rect() self.screen_rect = self.screen.get_rect() # Start each new asteroid near the middle of the screen self.rect.centerx = self.screen_rect.right self.rect.centery = self.screen_rect.centery # Store the bullet's position as a decimal value self.x = float(self.rect.x) def blitme(self) -> None: """Draw the asteroid at it's current location""" self.screen.blit(self.image, self.rect) def update(self) -> None: """Move the bullet up on the screen""" # Update the decimal position of the bullet self.x -= self.speed_factor # Update the rect position self.rect.x = self.x
from math import sqrt from numpy import dot, argmax, zeros import numpy as np from random import sample import random def fast_norm(x): """ Returns norm-2 of a 1-D numpy array. """ return sqrt(dot(x, x.T)) def compet(x): """ Returns a 1-D numpy array with the same size as x, where the element having the index of the maximum value in x has value 1, others have value 0. """ idx = argmax(x) res = zeros((len(x))) res[idx] = 1 return(res) def euclidean_distance(a, b): """ Returns Euclidean distance between 2 vectors. """ x = a - b return(fast_norm(x)) def default_bias_function(biases, win_idx): """ Default function that reduces bias value of winner neuron and increases bias value of other neurons """ biases = biases * 0.9 biases[win_idx] = biases[win_idx] / 0.9 - 0.2 return biases def default_non_bias_function(biases, win_idx): return biases def default_learning_rate_decay_function(learning_rate, iteration, decay_rate): return learning_rate / (1 + decay_rate * iteration) def default_radius_decay_function(sigma, iteration, decay_rate): return sigma / (1 + decay_rate * iteration) def split_data(data, val_size=0.2, proportional=True): if val_size == 0: return data, data[:0] if proportional: y = data[:,-1] sort_idx = np.argsort(y) val, start_idx= np.unique(y[sort_idx], return_index=True) indices = np.split(sort_idx, start_idx[1:]) val_indices = [] for idx_list in indices: n = len(idx_list) val_indices += idx_list[(sample(range(n), round(n*val_size)))].tolist() val_indices = sorted(val_indices) else: n = len(data) val_indices = sorted(sample(range(n), round(n*val_size))) return np.delete(data, val_indices, axis=0), data[val_indices] def limit_range(x, feature_range = (0, 1)): x[np.where(x > feature_range[1])] = feature_range[1] x[np.where(x < feature_range[0])] = feature_range[0] return x def weighted_sampling(weights, sample_size): """ Returns a weighted sample with replacement. """ totals = np.cumsum(weights) sample = [] for i in range(sample_size): rnd = random.random() * totals[-1] idx = np.searchsorted(totals, rnd, 'right') sample.append(idx) return sample
from tkinter import * root = Tk() root.geometry("300x200") root.title('Code Core') root.configure(background='light gray') def chang_txt(): l1.config(text=e1.get()) l1=Label(root, text = " Hello World!",fg = "light green",bg = "darkgreen",font = "tahoma 16") l1.grid(row=0,column=0) #l1.place(x=10,y=10) Label(root,text="Enter your name: ").grid(row=1,column=0) e1=Entry(root) e1.grid(row=1,column=1) button = Button(root,text='Change text',command=chang_txt) button.grid(row=2,column=0) root.mainloop()
from stone import stone from scissors import scissors from palm import palm import random def judgment(a): if a == "stone": stone() elif a == "scissors": scissors() else: palm() number = 0 while True: if number > 0: c = input("Do you want to continue the game? Please enter n to exit, enter other to continue the game.") if c == "n": break else: number = 0 else: while number == 0: a = input("Please enter stone, scissors and paper:") if a== "stone" or a== "scissors" or a== "paper": number += 1 else: print("Is the input wrong, please re-enter") print("--------Battle process--------") b = random.randint(1,3) if b == 1: print("The computer came out: stone") stone() print("You out:") judgment(a) elif b == 2: print("The computer came out: scissors") scissors() print("You out:") judgment(a) else: print("The computer came out: paper") palm() print("You out:") judgment(a) print("--------Result--------") if a == "stone": if b == 1: print("Tie") elif b == 2: print("You win") else: print("The computer win") elif a == "scissors": if b == 1: print("The computer win") elif b == 2: print("Tie") else: print("You win") else: if b == 1: print("You win") elif b == 2: print("The computer win") else: print("Tie") number += 1
''' a='soft' b='warica' print(f' {b[-1::-1]}{a[-1::-1]} is my college') name='shoobham gadeula' print(name[-5:0:-1]) ''' ''' number=int(input("enter number ")) if number % 2 == 0: print('number is even') else: print("number is odd") '''
import random secretNumber = random.randint(1,20) global numberOfGuesses numberOfGuesses = 0 def game(secretNumber): print("Am thinking of a number between 1 and 20.") print("Take a guess.") guessLimit = 6 #global numberOfGuesses while numberOfGuesses <= guessLimit: yourNumber = int(input()) numberOfGuesses = numberOfGuesses + 1 if yourNumber < secretNumber: print("your guess is to low.") elif yourNumber > secretNumber: print("Your guess is too high.") else: break if yourNumber == secretNumber: print("Good job! You guessed my number in " + str(numberOfGuesses) + " guesses !") else: print('Nope. The number I was thinking of was ' + str(secretNumber)) game(secretNumber)
import numpy as np import pandas as pd #### creating dataframes, adding and dropping columns df = pd.DataFrame(np.arange(1,10).reshape(3,3),['A','B','C'],['w','x','y']) df.columns = ['W','X','Y'] # change column names df['Z']=df['X']+df['Y'] # new column with values X+Y df['XX']=df.apply(lambda row: row['X']*2, axis=1) # new column with values twice of column X df['YY']=1 # new column of ones df.insert(2, column='D', value=100) # new column of '100's called 'D' at position 2 (3rd column) df.drop('B',axis=0, inplace=True) # drop row df.drop('Z',axis=1) # drop column Z = df.pop('Z') # drop column and store series to a variable #### selecting from dataframes # select columns df.X # column X (does not work when column name has spaces) df['X'] # column X df[['X','Y']] # columns X and Y # select rows using loc and iloc # can also use ix, but it's slightly tricky to use: https://stackoverflow.com/questions/31593201/pandas-iloc-vs-ix-vs-loc-explanation # ix is useful for mixing usage of loc and iloc (use both labels and positions at the same time) # returns a series if single row selected df.loc['A'] # row A df.loc['A':] # row A onwards df.loc[:'X'] # until row X (inclusive!) df.loc['A','X'] # row A, column X df.loc[['A','doesnotexist']] # return row with NaN for doesnotexist, check if exists via "doesnotexist" in df.index df.loc[['A','C'],['X','Y']] # rows A and C, columns X and Y df.iloc[0] # row at position 0 df.iloc[:,0:3] # column from position 0 to before 3 df.iloc[[0,1],[0,1]] # rows 0 and 1, and columns 0 and 1 #### broadcasting operations df['X'].add(5) # == df['X'] + 5 df['X'].sub(5) # == df['X'] - 5 == df['X'].subtract(5) df['X'].mul(5) # == df['X'] * 5 == df['X'].multiply(5) df['X'].div(5) # == df['X'] / 5 == df['X'].divide(5) #### basic attributes and methods # general data exploration df.info() # type, index, columns, dtypes, memory usage - printed automatically df.head() df.tail() df.sample(n=2) # return 2 random rows df.sample(frac=.25) # return 25% random rows df.nlargest(n=2, columns='X') # returns 2 rows for largest X df.nsmallest(n=2, columns='X') # returns 2 rows for smallest X df.index # RangeIndex df.columns # nparray of column names df.axes # index and columns df.values # nparray of nparrays df.dtypes # series df.shape # tuple df.get_dtype_counts() # count number of columns for each datatype df.sum() # sums summable columns into a series (where column names become the index) df.sum(axis = "columns") # methods for columns df.sort_values(by=['X','Y'], ascending=[False,True]) # sort df by column X (descending) then Y (ascending) df['X'].isnull() # series of booleans df['X'].rank() # rank values in column X in ascending order df['X'].unique() # nparray: unique values from column X df['X'].nunique() # number of unique values from column X, does not include null by default! df['X'].value_counts() # returns count of each value from column X df.drop_duplicates(subset = ['X'], keep ="first") # keep only first instance of X values # index-related df.set_index('X') # sets column X as the index df.set_index('Y') # sets column Y as the index, removes column X! df.reset_index() # resets index (removes current index, resets dataframe, inserts new index starting from 0) df.sort_index() # important for optimization # parse columns df.astype(int) # convert to int df['X'].astype("category") # convert to category (important for optimization) pd.to_datetime(df['X']) # convert to date (important for optimization) # rename columns df.rename(columns = {'X': 'A', 'Y': 'B'}, inplace=True) df.columns = ['X', 'Y', 'Z', 'XX', 'YY', 'ZZ'] #### selecting with conditional operators # create mask, which is a series of booleans mask1 = df['X'] < 5 mask2 = df['Y'].isin([4,5,6]) mask3 = df['Y'].isnull() mask4 = df['Y'].notnull() mask5 = df['Y'].between(4,6) mask6 = df['Y'].duplicated(keep = False) # return True if duplicated mask7 = ~df['Y'].duplicated(keep = False) # return True if unique # use mask to select from dataframe df[mask1] # return rows where X<5 df[mask1][['X','Y']] # return only columns X and Y df[mask1 & mask2] df[mask1 | mask2] df[(mask1 | mask2) & mask3] df.where(mask1) # return NaN for entire row when condition not met # alernatively, use query (possibly better performance) # ensure column names dont have spaces: use df.columns = [col.replace(" ","_") for col in df.columns] df.query('X < 5') # return rows where X<5 df.query('X in [4,5,6]') df.query('X not in [4,5,6]') #### missing values - dropna and fillna df.dropna() # removes any rows with NaN values (how = "any" by default) df.dropna(how="all") # removes rows with all NaN values df.dropna(subset=["X"]) # remove rows where value is NaN in column X df.dropna(axis=1,thresh=10) # drop all columns containing at least 10 NaN values df.fillna(0) # replace all NaN values with 0 df['Y'].fillna(0, inplace=True) # replace all NaN values in column 'Y' with 0 df['X'].fillna(value=df['XX'].mean()) # replace NaN on column X with mean of column XX #### groupby with aggregate function df.groupby('X').describe() #### concat df1 = pd.DataFrame(np.random.randn(5, 5), columns=['a', 'b', 'c', 'd', 'e'], index=['v','w','x','y','z']) df2 = pd.DataFrame(np.random.randn(5, 5), columns=['a', 'b', 'c', 'd', 'e'], index=['v','w','x','y','z']) df3 = pd.DataFrame(np.random.randn(5, 5), columns=['a', 'b', 'c', 'd', 'e'], index=['v','w','x','y','z']) pd.concat([df1,df2,df3]) # concat vertically (match columns) pd.concat([df1,df2,df3],axis=1) # concat horizontally (match rows) #### merge (== join) left = pd.DataFrame([[1,'A'],[1,'B'],[2,'B']], columns=['C1','C2'], index=['I1','I2','I3']) right = pd.DataFrame([['B','C','D']], columns=['C2','C3','C4'], index=['I1']) pd.merge(left,right,how='inner',on='C2') # same as inner join in sql (concats horizontally) #### pivot tables pivot = {'A': ['foo','foo','foo','bar','bar','bar'], 'B': ['one','one','two','two','one','one'], 'C': ['x','y','x','y','x','y'], 'D': [1,3,2,5,4,1]} df = pd.DataFrame(pivot) df.pivot_table(values='D',index=['A','B'],columns=['C']) #### multi-level index dataframes (ie dataframes within dataframes) outside = ['G1','G1','G1','G2','G2','G2'] inside = [1,2,3,1,2,3] hier_index = pd.MultiIndex.from_tuples(list(zip(outside,inside))) df = pd.DataFrame(np.arange(1,13).reshape(6,2),hier_index,['A','B']) df.index.names = ['Groups','Num'] df.loc['G1'].loc[1]['A'] # access elements using multiple loc df.xs(1,level='Num') # return rows where 'num'=1 #### input output # df = pd.read_csv('data_2d.csv', header=None) # headers included by default # df.to_csv('out',index=False) # df = pd.read_excel('Excel.xlsx',sheetname='Sheet1') # df.to_excel('out.xlsx',sheet_name='NewSheet') # data = pd.read_html('somelink') # returns a list # don't use pandas to read sql (better alternatives available)
# 12create script that converts ranges into list of item multiplied by 10 import string from collections import OrderedDict r = range(1, 10) ls = [10 * item for item in r] # print(ls) # 13 convert range into strings ls_string = map(str, ls) for item in ls_string: # print(item) # remove duplicates from list a = [1, 1, 12, 2, 2, 3, 4, 5, 5] a = list(set(a)) # print(a) # If you want to keep the order, you need OrderedDict a = ["1", 1, "1", 2] a = list(OrderedDict.fromkeys(a)) print(a) # print ascii for letter in string.ascii_lowercase: print(letter)
#who will pay the bill import random def randomChoice(min,max): return random.randint(min,max) def whoWillPay(): names=input("Enter Names separated by comma") namesList = names.split(',') numberOfPayer = len(namesList) randomName = randomChoice(0,numberOfPayer-1) print(randomName) paidBy = namesList[randomName] print(paidBy) print("Today is meal brought by"+paidBy) whoWillPay()
age=10 if age<18: print("fuck u") elif age<25: print('fuck others') elif age<30: print('fucked by wife') else: print('fucked all th life') #switch #ternary
from functools import partial import colors as c print(c.color('my string', fg='blue')) print(c.color('some text', fg='red', bg='yellow', style='underline')) print() for i in range(256): if i % 8 != 7: print(c.color('Color #{0}'.format(i).ljust(10), fg=i), end='|') else: print(c.color('Color #{0}'.format(i).ljust(10), fg=i), end='\n') print() # c.color(text*, fg, bg, style) print(c.color('orange on gray', 'orange', 'gray')) print(c.color('nice color', 'white', '#8a2be2')) print(c.red('This is red')) print(c.green('This is green')) print(c.blue('This is blue')) print(c.red('red on blue', bg='blue')) print(c.green('green on black', bg='black', style='underline')) print(c.red('very important', style='bold+underline')) important = partial(c.color, fg='red', style='bold+negative+blink') print(important('this is very important!')) print() print(c.color("none", style="none")) print(c.color("bold", style="bold")) print(c.color("faint", style="faint")) print(c.color("italic", style="italic")) print(c.color("underline", style="underline")) print(c.color("blink", style="blink")) print(c.color("blink2", style="blink2")) print(c.color("negative", style="negative")) print(c.color("concealed", style="concealed")) print(c.color("crossed", style="crossed")) print()
for num in range(1, 101): if num % 15 is 0: print("buzzfizz") elif num % 3 is 0: print("kizz") elif num % 5 is 0: print("juzz") else: print(num)
""" Random Name Generator """ from collections import deque import random import importlib import warnings def fetch_words(list_name): """ Returns a tuple of words from the word libraries contained here. """ mod = importlib.import_module( '.lists.%s' % list_name, package='randomname') return mod.WORDS def generate(wordlists, wordcount=1, separator=' '): """ Given an iterable of wordlists to use, generates a random name. :param wordlists: a list of wordlists to use (from 'randomname.lists') :param int wordcount: number of words to generate :param str separator: a word separator to use (defaults to a single space) """ wordlist = WordList() for wlist in wordlists: wordlist.add_words(fetch_words(wlist)) name = [] for _ in range(wordcount): name.append(wordlist.random_word()) return separator.join(name) def generate_human_name(male=True, female=True, separator=' '): """ Generate a random American-sounding name like 'John Smith'. Gender can be selected by toggling male/female. """ firstnames = WordList() if male: firstnames.add_words(fetch_words('names_male')) if female: firstnames.add_words(fetch_words('names_female')) lastnames = WordList(words=fetch_words('surnames_american')) names = [] names.append(firstnames.random_word()) names.append(lastnames.random_word()) return separator.join(names) def generate_hostname(wordcount=2, separator='-'): """ Useful for generating machine hostnames. Uses a combination of descriptors and nouns to create interesting, easy to read names. Adjectives and actions will be used for all but the final word in the name, which will instead be comprised of animals, male/female names, and occupations. """ words = [] for _ in range(wordcount - 1): wl = WordList() wl.add_wordlist('adjectives') wl.add_wordlist('actions') wl.add_wordlist('personalities') wl.add_wordlist('visual_colors') wl.add_wordlist('visual_pattern') words.append(wl.random_word()) wl = WordList() wl.add_wordlist('animals') wl.add_wordlist('occupations') wl.add_wordlist('fruit') wl.add_wordlist('mnemonic') words.append(wl.random_word()) return separator.join(words).lower() class WordList: def __init__(self, words=None): """ Initialize the word list. Optionally pass a list of words to this constructor to pre-initialize the list. """ if words is None: words = [] self._words = deque(words) @classmethod def load_from_file(cls, filename): """ Create a new WordList from the specified filename. Returns the WordList object. """ wl = cls() wl.add_file(filename) return wl @property def words(self): """ Returns a read-only tuple version of the entire wordlist """ return tuple(self._words) def random_word(self): """ Returns a random word from the list, as a string. """ return random.choice(self._words) def add_words(self, words): """ Given an iterable of words, add them to this list. """ self._words.extend(words) def add_wordlist(self, listname): """ Add words from one of the built-in wordlists (from randomname.lists) """ self.add_words(fetch_words(listname)) def add_file(self, filename): """ Given a path to a file containing a word list (one word per line), load all the words into this WordList in an append-like fashion. """ with open(filename, 'r') as fh: self._words.extend(fh.read().splitlines())
# ATP RACIOCÍNIO COMPUTACIONAL # Importa biblioteca datetime (data e hora) from datetime import datetime # VARIÁVEIS GLOBAIS - há outras dentro das funções meuNome = 'Isabela Milene Paniagua Zanardi' # Função OBTER LIMITE - Etapas 1 e 2 def obter_limite(): print('Bem-vindo à Loja da', meuNome) cargo = input('Faremos sua análise de crédito pessoal. Por favor, informe seu cargo atual:') salario = float(input('Informe o seu salário:')) dataNascimento = (input('Digite sua data de nascimento no formato dd/mm/aaaa:')) hoje = datetime.now() anoAtual = int(hoje.strftime('%Y')) anoNascimento = int(dataNascimento.split("/")[2]) global idade idade = anoAtual - anoNascimento global limite limite = float(salario * (idade / 1.000) + 100) print('Você tem {} anos, e seu cargo é {}\n Seu limite pré-aprovado é de R${}'.format(idade,cargo,limite)) # Função PERGUNTA DE CADASTRO DE PRODUTO def cadastrar_produtos(): global nProdutos nProdutos = int(input('Quantos produtos você deseja cadastrar?')) if nProdutos > 0: for i in range(0, nProdutos): verificar_produto() i += 1 else: print('Não há nenhum produto a ser cadastrado. Fim da análise') exit() # Função VERIFICAR PRODUTO - Guarda os produtos e os valores em uma lista. def verificar_produto(): global listaProdutos listaProdutos = [] listaProdutos.append(input('Digite o nome do produto:')) global listaValores listaValores = [] listaValores.append(float(input('Digite o valor do produto:'))) global soma soma = sum((listaValores)) # EXECUÇÃO DO PROGRAMA while True: obter_limite() cadastrar_produtos() # TERMINANDO A EXECUÇÃO print('Você cadastrou {} produtos'.format(nProdutos)) # 1) CÁLCULO DOS DESCONTOS primeiroNome = (meuNome.split(" ")[0]) if len(primeiroNome) <= soma <= idade: print('Parabéns! Você terá um desconto de', len(meuNome), '%!') print('O preço do produto com desconto é de', soma - (soma * (len(meuNome) / 100))) else: print('Infelizmente você não terá mais descontos') # 2) CÁLCULO DO PARCELAMENTO if soma <= (limite * 0.6): print('Limite Liberado!') elif (limite * 0.6) < soma <= (limite * 0.9): print('Valor liberado para parcelar em até 2 vezes') elif (limite * 0.9) < soma <= limite: print('Valor liberado para parcelar em 3 ou mais vezes') else: print('Bloqueado parcelamento') terminar = str(input('Você gostaria de realizar uma nova análise? Digite "sim" para nova análise. Digite "não" para finalizar')) if terminar == "sim": continue else: exit() '''Eu NEM ACREDITO que consegui!!! Tenho plena consciência de que tem muita coisa pra melhorar, mas a partir de agora eu entendi os fundamentos :) '''
# Christopher Lamy print('Hello. What language would you like to learn how to say "Hello" in?')# Question #Options print('A: Creole.') print('B: Swahili.') print('C: Swedish ') #Input option = input() #Choice of language user would like to learn. if option == 'A': print('Alo') elif option == 'B': print('Hujambo!') elif option == 'C': print('Hej') #The end print('Good Bye!') # make sure that your code contains comments explaining your logic!
# test_TSH_Test_Diagnostics.py def test_TSH_diagnosis_normal(): '''Unit test for a list of normal TSH values This function is a unit test that receives a string of TSH values and tests whether the TSH_diagnosis code correctly orders the test results from low to high and outputs the correct diagnosis. Args: line (str): line containing TSH test results diagnosis (str): asserted patient diagnosis TSH_sorted_numbers (list): asserted sorted test results (low to high) ''' from TSH_Test_Diagnosis import TSH_diagnosis line = "TSH,2.4,3.4,1.4,1.8,3.1,2.7,1.9,2.5" (TSH_sorted_numbers, diagnosis) = TSH_diagnosis(line) assert diagnosis == "normal thyroid function" assert TSH_sorted_numbers == [1.4, 1.8, 1.9, 2.4, 2.5, 2.7, 3.1, 3.4] def test_TSH_diagnosis_hyper(): '''Unit test for a list of TSH values corresponding to hyperthyroidism This function is a unit test that receives a string of TSH values and tests whether the TSH_diagnosis code correctly orders the test results from low to high and outputs the correct diagnosis. Args: line (str): line containing TSH test results diagnosis (str): asserted patient diagnosis TSH_sorted_numbers (list): asserted sorted test results (low to high) ''' from TSH_Test_Diagnosis import TSH_diagnosis line = "TSH,1.5,2.7,3.2,3.4,0.7,3.0,0.5,2.4,3.4" (TSH_sorted_numbers, diagnosis) = TSH_diagnosis(line) assert diagnosis == "hyperthyroidism" assert TSH_sorted_numbers == [0.5, 0.7, 1.5, 2.4, 2.7, 3.0, 3.2, 3.4, 3.4] def test_TSH_diagnosis_hypo(): '''Unit test for a list of TSH values corresponding to hypothyroidism This function is a unit test that receives a string of TSH values and tests whether the TSH_diagnosis code correctly orders the test results from low to high and outputs the correct diagnosis. Args: line (str): line containing TSH test results diagnosis (str): asserted patient diagnosis TSH_sorted_numbers (list): asserted sorted test results (low to high) ''' from TSH_Test_Diagnosis import TSH_diagnosis line = "TSH,3.7,3.2,4.3,5.2,3.4,3.6,4.2,3.6,3.2" (TSH_sorted_numbers, diagnosis) = TSH_diagnosis(line) assert diagnosis == "hypothyroidism" assert TSH_sorted_numbers == [3.2, 3.2, 3.4, 3.6, 3.6, 3.7, 4.2, 4.3, 5.2]
#https://brilliant.org/wiki/sorting-algorithms/#sorting-algorithms #basically just trying to get in some coding practice in my free time import random def mergeSort(x): if len(x) < 2: return x results = [] mid = len(x) // 2 y = mergeSort(x[:mid]) z = mergeSort(x[mid:]) while (len(y) > 0) and (len(z) > 0): if y[0] > z[0]: results.append(z[0]) z.pop(0) else: results.append(y[0]) y.pop(0) results += y results += z return results def insertionSort(x): if len(x) == 0: return x results = [] results.append(x[0]) x.pop(0) while len(x) > 0: i = len(results) - 1 while i >= 0: if x[0] > results[i]: results.insert(i + 1, x[0]) x.pop(0) break elif i == 0: results = [x[0]] + results x.pop(0) break else: i -= 1 return results def bubbleSort(x): results = [] while len(x) > 1: max = len(x) - 1 for y in range(0, max): if x[y] > x[y + 1]: temp = x[y] x[y] = x[y + 1] x[y + 1] = temp results = [x[max]] + results x.pop(max) return [x[0]] + results def quickSort(x): if len(x) < 2: return x smaller = [] larger = [] same = [] rand = random.randint(0, len(x) - 1) pivot = x[rand] for y in x: if y < pivot: smaller.append(y) elif y > pivot: larger.append(y) else: same.append(y) return quickSort(smaller) + same + quickSort(larger)
#ASSIGNMENT OPERATORS no1=10 no1+=2 print(no1) no1-=2 print(no1)
word={} data=input("Enter String ") dat=list(data) for i in dat: if(i not in word): word.update({i:1}) else: print("First Repeating Letter: ",i) break print(word)
#7 VOWELS def countvow(str): set1=set() count=0 set2={'a','e','i','o','u','A','E','I','O','U'} for i in str: if(i in set2): count+=1 set1.add(i) else: pass if(count!=0): print("No of vowels=",count) else: print("No Vowels Exist") str=input("Enter String: ") countvow(str)
top=-1 stack=[] size=int(input("Enter Size of Stack: ")) def push(): global stack global size global top element=int(input("Enter Element To Push: ")) if(top<size): top+=1 stack.insert(top,element) elif(top==size): print("Stack Full") def pop(): global stack global size global top if(top<0): print("Stack Empty") else: element=stack[top] top-=1 print(element,"Was Removed") def display(): global top global stack for i in range(0,top+1): print(stack[i]) op=int(input("Enter Your Choice: 1.Push 2.Pop 3.Display 4.Exit")) while(op!=4): if(op==1): push() op = int(input("Enter Your Choice: 1.Push 2.Pop 3.Display 4.Exit")) elif(op==2): pop() op = int(input("Enter Your Choice: 1.Push 2.Pop 3.Display 4.Exit")) elif(op==3): display() op = int(input("Enter Your Choice: 1.Push 2.Pop 3.Display 4.Exit")) elif(op==4): break
#Input marks and print Grade of Student math=int(input("Enter Marks in maths ")) sc=int(input("Enter Marks in Science ")) comp=int(input("Enter Marks in Computer Science ")) sum=math+sc+comp if(sum>140): print("Grade A+") elif(sum>130&sum<=140): print("Grade A") elif(sum>120&sum<=130): print("Grade B+") elif(sum>110&sum<=120): print("Grade B") elif(sum>100&sum<=110): print("Grade C+") elif(sum>90&sum<=100): print("Grade C") else: print("Grade F")
tup=(1,2,3,4,7,3,"a") print(tup) # tup[0]=100 immutable #insersion Order preserved print(3 in tup) tup2=(100,50) employees=[(101,"Ayush",22,22000),(102,"John",29,23000),(103,"David",45,18000)] for i in employees: print(i) #to get only names for i in employees: print(i[1]) for i in employees: if(i[3]>20000): print(i)
no=int(input("Enter a no ")) if(no<0): print("Negative") elif(no==0): print("Neither negative or positive") else: print("Positive")
set=set() print(type(set)) set={10,20,20,10,40} print(set) #insersion Order not preserved set.add(105) print(set) print(set.pop()) days1={"Monday","Tuesday","Wednesday","Thursday"} days2={"Friday","Saturday","Sunday"} #union print(days1|days2) #or print(days1.union(days2)) #intersection set1={1,2,5,7,8} set2={3,4,5,9,8} print(set1&set2) #or print(set1.intersection(set2)) #Difference print(set1-set2) college={"Sachin","Ayush","John","Ron","Jacob"} failed={"Ayush","Rahul","Ron"} passed=college-failed print(passed)
# def cartesian(lst1,lst2): # tup=() # for i in lst1: # for j in lst2: # tup=(i,j) # print(tup) # # n1=int(input("Enter Size of List 1: ")) # n2=int(input("Enter Size of List 2: ")) # lst1=[] # lst2=[] # for i in range(0,n1): # el=int(input("Enter Element of List 1: ")) # lst1.append(el) # for j in range(0,n2): # elm=int(input("Enter Element of List 2: ")) # lst2.append(elm) # cartesian(lst1,lst2) #OR A=[1,2,3] B=[4,5,6] cartesianproduct=[(a,b) for a in A for b in B] print(cartesianproduct)
Vlr1 =int(input("ingrese primer numero")) Vlr2 =int(input("ingrese segundo numero")) Vlr3 =int(input("ingrese tercer numero")) suma = int(Vlr1) + int(Vlr2) + int(Vlr3) resta = int(Vlr1) - int(Vlr2) - int(Vlr3) multi = int(Vlr1) * int(Vlr2) * int(Vlr3) print("La suma es:.{}".format(suma)) print("La resta es:.{}".format(resta)) print("La multiplicacion es:.{}".format(multi))
#GERSON ADILSON BOLVITO LOPEZ 5TO BIPC #Ejercicio 2 #ingrese un valor y mostrar los numeros desde el menos -10 al numero ingresado print("bienvenido al programa".center(50, "_")) num = int(input("ingrese valor: ")) contador = -10 while contador <= num: print (contador) contador+=1
#*-* coding:utf-8 *-* print "hello" print u"你好" list1 = [1,2,3,4,5] word = list1.pop(-1) print word print list1 print "list this".split(' ')
import numpy as np def mean_squared_error(estimates, targets): # """ # Mean squared error measures the average of the square of the errors (the # average squared difference between the estimated values and what is # estimated. The formula is: # # MSE = (1 / n) * \sum_{i=1}^{n} (Y_i - Yhat_i)^2 # # Implement this formula here, using numpy and return the computed MSE # # https://en.wikipedia.org/wiki/Mean_squared_error # # """test_mean_squared_error # test_generate_regression_data # test_polynomial_regression # test_perceptron # test_transform_data n = estimates.shape[0] total = 0 for i in range(n): total += ((estimates[i] - targets[i])**2) mse = (1/n) * total return mse
# Generate the Twitter query for a specified file def load_query(query_path): # Create a list of the key phrases keys = [] # Open the file and read each line with open(query_path, 'r') as file: for line in file: parsed = line.strip() # Verify that the line is not empty if len(parsed) > 0: # Add that line to the list of keywords keys.append(parsed) # If there are too many keywords, throw an error # See limit specified at https://developer.twitter.com/en/docs/twitter-api/v1/tweets/search/guides/standard-operators if len(keys) > 10: raise Exception("Search is too complex, limit to 10 keykeys") # Join keywords together, surrounded by quotes and OR operators query = "" for i, word in enumerate(keys): query += f'"{word}" ' if i < len(keys) - 1: query += 'OR ' # Return the generated query return query
# -*- coding: utf-8 -*- def array_swap_items(input_array, index1, index2): """ Swap 2 items in an array :param array: the array where items are swapped :param index1: element to swap :param index2: element to swap :return: the array with items swapped """ output_array = input_array.copy() temp = output_array[index1] output_array[index1] = output_array[index2] output_array[index2] = temp return output_array
import datetime as dt import time as tm print(tm.time()) print([1, 3]+[3, 7]) print("hh"+str(2)) dtnow = dt.datetime.fromtimestamp(tm.time()) # get year, month, day, etc.from a datetime dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second delta = dt.timedelta(days=-100, hours=2) # create a timedelta of 100 days print(delta) today = dt.date.today() # 现在的本地时间 print(today) n = today+delta # the date 100 days ago print(n) print(today > n) # compare dates
#1 to 10 # count = 1 # while count <= 10: # print count # count = count + 1 # n to m # start = int(raw_input("start number: ")) # end = int(raw_input("end number? ")) # while start <= end: # print start # start = start +1 #odd numbers # count = 1 # while count <=10: # if count % 2 != 0: # print count # count = count + 1 #How many coins # coins = 0 # print ("your have %d coins.") % coins # cond = True # while cond: # coinQ = raw_input("do you want more coins? ") # coinA = coinQ # if coinA == "yes": # coins = coins + 1 # print ("you have %d coins.") % coins # else: # cond = False # print("bye") #print a sqaure # size = 5 # i = 0 # while i <= size: # print ('*' * size) # i = i + 1 #Print a Square II # size = int(raw_input("how big is the square? " )) # i = 0 # while i <= size: # print ("*" * size) # i = i + 1 #print a box # width = int(raw_input("what is the width? ")) # height = int(raw_input("height? ")) # i = 0 # innerW = width - 2 # print("*" * width) # while i < (height - 2) : # print ("*" + (innerW * " ") + "*") # i = i +1 # print ("*" * width) #print triangle # * # *** # ***** # ******* # space = 3 # starC = 1 # while starC <= 7: # print ((" " * space) + ("*" * starC)) # space = space - 1 # starC = starC + 2 #print a Triangle 2 height = int(raw_input("Give Height: ")) space = (height * 2) starC = 1 while starC <= height: print ((" " * space) + ("*" * starC)) space = space - 1 starC = starC + 2 #multiplication table # integer = 1 # multip = 1 # while integer <= 10: # statement = ("%d times %d equals") % (integer, multip) # total = integer * multip # print statement, total # multip = multip + 1 # if multip > 10: # multip = 1 # integer = integer + 1 #Print a Banner # statement = raw_input("wright a statememt: ") # length = len(statement) + 4 # print ("*" * length) # print ("*" + " " + statement + " " + "*") # print ("*" * length) #triangle numbers # triN = 1 # triC = 1 # while triN <= 100: # triC = triN * (triN + 1)/2 # print triN, "is equal to ", triC # triN = triN + 1 #find factors of given number # number = int(raw_input("What is your number: ")) # i = 1 # check = number % i # while i <= number: # if number % i == 0: # print i # i = i + 1 #blastoff # import time # timer = (raw_input("Set count down timer: ")) # i = int(timer) # if i > 20: # print ("timer to high!") # while i <= 20 and i > -1: # if i >= 0: # print i # i = i - 1 # if i < 0: # time.sleep(2) # print ("lift off!!!!!") #Guess a number import random # secretNumber = random.randint(1, 10) # limit = 5 # cond = True # tryAgain = False # while cond: # guess = int(raw_input("guess the number: ")) # if guess == secretNumber: # print ('Hooray') # cond = False # tryAgain = True # else: # if guess > secretNumber: # print guess, 'Try again - number is too high' # limit = limit - 1 # print 'lives left: ', limit # if guess < secretNumber: # print guess, 'Try again - number is too low' # limit = limit - 1 # print 'lives left:', limit # if limit <= 0: # print('GAME OVER') # cond = False # tryAgain = True # while tryAgain: # again = (raw_input("play again? ")) # if again == "yes": # tryAgain = False # cond = True # limit = 5 # if again == "no": # print ('Bye')
choiceList = ["Chipotle", "Farm Burger" ,"RuSan's", "Exit"] # def counterTrack(count): # if count >= 5: # print "Limit reached fatty" def userChoice(): user_choice = int(raw_input("Pick a resturant - 1: Chipotle 2: Farm Burger 3: RuSan's 0: Exit " )) return user_choice def List_of_resturant(user_number): if user_number == 1: rchoice = "Chipotle" return rchoice elif user_number == 2: rchoice = "Farm Burger" return rchoice elif user_number == 3: rchoice = "RuSan's" return rchoice elif user_number == 0: rchoice = "exit" return rchoice else: rchoice = "INVALID SELECTION" return rchoice def printOutput(user_number): choice = List_of_resturant(user_number) return choice # print "you selected %s" % choice # listNumber = user_number - 1 # print choiceList[listNumber] # def quit_tracker(): # user_choice_exit = userChoice() # if user_choice_exit == 0: # exit_test = False # return exit_test # else: # exit_test = True # return exit_test def lunch_tracker(): choice_num = userChoice() count = 0 while count <= 5: print "you selected %s" % printOutput(choice_num) count += 1 print "you've had enough fatty!" exit_no = False lunch_tracker()
from turtle import * def center_turtle(): up() forward(150) left(90) left(270) down() def draw_a_square(): forward(100) right(90) forward(100) right(90) forward(100) right(90) forward(100) def fly_turtle_fly(): up() right(90) forward(150) down() def draw_a_circle(): # begin_fill() # fillcolor('red') pencolor('orange') width(1) circle(100) # end_fill() def draw_a_star(): for i in range(5): forward(125) right(144) def draw_h(): left(90) forward(100) up() right(180) forward(50) down() right(270) forward(50) up() left(90) forward(50) right(180) down() forward(100) def draw_a(): left(75) forward(100) right(150) forward(100) up() left(180) forward(50) down() left(75) forward(25) up() right(180) forward(60) right(90) forward(50) left(90) def main(): # center_turtle() # draw_a_circle() # up() # left(90) # forward(75) # down() # draw_a_star() # draw_a_square() # fly_turtle_fly() # draw_a_square() # draw_a_square() draw_h() draw_a() mainloop() main ()