text
stringlengths
37
1.41M
a = 0 x = 0 for i in range(10): a = int(input("Введите число :")) x += a y = x / 10 print(y)
x = int(input("введите число ")) y = int(input("введите число ")) if x % 2 != 0 and y % 2 != 0: print(x, y) else: print("(((((")
# Tam Fredrick Kofi # Date: 21/09/2014 # file: kofi.py # UNI: fkt2105 # #*************************************** ### question 3 ### Python programme to find your age in days ### Greet the person print( '''Hello there, I hope you are fine! Let me help me you to find your age in days''') ### Ask for name of person print('Please what is your name?' ) name_of_person = raw_input( 'Your name please?') if name_of_person == 'kofi': print( 'Welcome Mr.Tam') else: print( 'Welcome new friend, my dear %s' %name_of_person) print( '''Now, let us get down to business. Please enter your date of birth in the format year,month,day, numerically''' ) ### get data from the person bd_y = input("Year: ") bd_m = input("Month (1-12): ") bd_d = input("Day: ") ### import date form datetime module from datetime import date ### assign variable now to the current date now = date.today() birthdate = date(int(bd_y), int(bd_m), int(bd_d)) ### assign variable ''age'' to result of calculation of age difference age = now-birthdate print "Your age is %s" % age ### since minimum age is 110 years, no limitations are needed
import random giving_up = 0 def wake_up(): global giving_up print "When I woke up..." late_for_class = random.randint (0,6) if late_for_class == 1: giving_up += 5 print "I was late for class." stuff_due = random.randint (0,5) if stuff_due == 1: giving_up += 5 print "Assignments were due today." nightmare = random.randint (0,5) if nightmare == 1: giving_up += 5 print "I had a nightmare." hours_slept = random.randint (4,12) if hours_slept < 6: giving_up += 5 print "I slept too little." if hours_slept > 10: giving_up += 5 print "I slept too much." took_medication = random.randint (0,4) if took_medication == 0: giving_up += 5 print "I forgot to take my medication." bad_weather = random.randint (0,4) if bad_weather == 1: giving_up += 3 print "The weather was bad." if late_for_class != 1 and stuff_due != 1 and nightmare != 1 and took_medication != 0 and bad_weather != 1: print "Everything was okay." def what_happened(): global giving_up physical_health = random.randint (1,3) if physical_health < 3: giving_up += 3 print "I didn't feel well." mental_health = random.randint (1,3) if mental_health < 3: giving_up += 3 print "I wasn't in a good mood." self_esteem = random.randint (-2, 2) if self_esteem < 0: giving_up += 3 print "I didn't feel good about myself." nourished = random.randint (0,4) if nourished == 0: giving_up += 2 print "I didn't eat enough food." bad_news = random.randint (0,6) if bad_news == 1: giving_up += 2 print "I heard something bad happened today." wake_up() hour = 0 while hour < 12: if hour == 0: print "\n" + str(hour+1) + " hour after waking up..." else: print "\n" + str(hour+1) + " hours after waking up..." what_happened() g = random.randint(1,100) if g > (int(float(giving_up)/3)): if g > giving_up: if hour < 11: print "I managed to get things done." if hour == 11: print "I managed to get through the whole day!" else: print "I couldn't get anything done." if hour == 11: print "I managed to get through the day!" else: print "I couldn't do anything else today." break hour += 1
from numpy import sin, cos import matplotlib.pyplot as plt import scipy.integrate as integrate import matplotlib.animation as animation import matplotlib import matplotlib.pyplot as plt import numpy as np def multiplot(x1, y1, y1_2, x2, y2, y2_2, color1="blue", color2="orange", subtitle="", x1_label="", y1_label="", x2_label="", y2_label=""): fig, (ax1, ax2) = plt.subplots(2, 1) fig.suptitle(subtitle) ax1.plot(x1, y1, color=color1) try: ax1.plot(x1, y1_2, color=color2) except: pass ax1.set_xlabel(x1_label) ax1.set_ylabel(y1_label) ax1.legend((f"m1 {y1_label}", f"m2 {y1_label}")) ax2.plot(x2, y2, color=color1) try: ax2.plot(x2, y2_2, color=color2) except: pass ax2.set_xlabel(x2_label) ax2.set_ylabel(y2_label) ax2.legend((f"m1 {y2_label}", f"m2 {y2_label}")) plt.show()
from tkinter import * def function(): print("that is function") root = Tk() myInput = Entry(root, text= "Click ME", width=100, bg='white', fg='black', borderwidth=5) myInput.pack() root.mainloop()
"""Using stacked decorators""" def bold(func): """Decorator function""" def wrapper(): """Decorator wrapper - the actual decorator""" return "<b>" + func() + "</b>" return wrapper def italic(func): """Decorator function""" def wrapper(): """Decorator wrapper - the actual decorator""" return "<i>" + func() + "</i>" return wrapper @bold @italic def formatted_text(): """Returns some text""" return "Python Rocks!" print() print(formatted_text()) print()
from tkinter import* import sqlite3 import tkinter.ttk as ttk import tkinter.messagebox as tkMessageBox root = Tk() root.title("Python: Simple CRUD Applition") screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() width = 700 height = 400 x = (screen_width/2) - (width/2) y = (screen_height/2) - (height/2) root.geometry('%dx%d+%d+%d' % (width, height, x, y)) root.resizable(0, 0) # ==================================METHODS============================================ def Database(): global conn, cursor conn = sqlite3.connect('pythontut.db') cursor = conn.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, firstname TEXT, lastname TEXT, gender TEXT, address TEXT, username TEXT, password TEXT)") def Read(): tree.delete(*tree.get_children()) Database() cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC") fetch = cursor.fetchall() # print(fetch) for data in fetch: tree.insert('', 'end', values=( data[1], data[2], data[3], data[4], data[5], data[6])) cursor.close() conn.close() # ==================================LIST WIDGET======================================== scrollbary = Scrollbar(root, orient=VERTICAL) scrollbarx = Scrollbar(root, orient=HORIZONTAL) tree = ttk.Treeview(root, columns=("Firstname", "Lastname", "Gender", "Address", "Username", "Password"), selectmode="extended", height=500, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set) scrollbary.config(command=tree.yview) scrollbary.pack(side=RIGHT, fill=Y) scrollbarx.config(command=tree.xview) scrollbarx.pack(side=BOTTOM, fill=X) tree.heading('Firstname', text="Firstname", anchor=W) tree.heading('Lastname', text="Lastname", anchor=W) tree.heading('Gender', text="Gender", anchor=W) tree.heading('Address', text="Address", anchor=W) tree.heading('Username', text="Username", anchor=W) tree.heading('Password', text="Password", anchor=W) tree.column('#0', stretch=NO, minwidth=0, width=0) tree.column('#1', stretch=NO, minwidth=0, width=80) tree.column('#2', stretch=NO, minwidth=0, width=120) tree.column('#3', stretch=NO, minwidth=0, width=80) tree.column('#4', stretch=NO, minwidth=0, width=150) tree.column('#5', stretch=NO, minwidth=0, width=120) tree.column('#6', stretch=NO, minwidth=0, width=120) tree.pack() # ==================================INITIALIZATION===================================== if __name__ == '__main__': Read() root.mainloop()
#List, Dictionary and Iteration Review ################################################################################### LISTS ################################################################################### ##Create a list called group_names which includes the name of every person in our group. group_names = ["Marisa", "Eliseo", "Aaron"] ##READ the List #Print the second element of the list: print(group_names[1]) #Identify the length of the list and print it in a sentence saying: Our group has _____ people. print("Our group has " + str(len(group_names)) ##Update the list: #Add a "Ellie" to the group! group_names.append("Ellie") print(group_names) #Reassign the fourth element to be "Jeff" group_names[3] = "Jeff" print(group_names) ##Iterate over the list #Print out EACH name separately. for person in group_names: print(person) #For each person in the group, print "The #____ person to arrive was _______" for x in range(len(group_names)): print("The #" + str(x + 1) + " person to arrive to our group was " + group_names[x] + ".") ################################################################################### DICTIONARIES ################################################################################### ##Create a dictionary called group_ice_cream, of all the students in our group and their favorite ice cream. group_ice_cream = {"Marisa": "Coffee", "Eliseo": "Rocky Road", "Aaron": "Cookie Dough"} #What aspects of this dictionary are keys? What aspects are values? ##Read the Dictionary #Print the second person in the dictionary. print(group_ice_cream[1]) #Print the second person in the dictionary's favorite ice cream flavor print(group_ice_cream["Eliseo"]) #Print the statement: "Our dictionary has _____ elements" print("Our dictionary has " + str(len(group_ice_cream)) + " elements.") ##Update the Dictionary #HOW DO I ADD SOMETHING TO A DICTIONARY? DO I APPEND? #Replace Eliseo's favorite ice cream with "?" group_ice_cream["Eliseo"] = "Coffee" ##Iterate over a dictionary #For each person in the dictionary, print "______'s favorite ice cream is _______" for name in group_ice_cream: print(name + "'s favorite ice cream is " + group_ice_cream[name]) ################################################################################### LISTS OF DICTIONARIES ################################################################################### ##Create a list called our_profiles that has a dictionary inside for each person in our group. The dictionary should contain the person's name, age, birthday, and favorite ice cream. our_profiles = [ {"name": "Marisa", "age": 28, "birthday": "08/08/1990", "fav_ice_cream": "Coffee"} {"name": "Eliseo", "age": 29, "birthday": "06/08/1990", "fav_ice_cream": "Rocky Road"} {"name": "Aaron", "age": 17, "birthday": "08/08/2002", "fav_ice_cream": "Cookie Dough"} ] ##Read our list of DICTIONARIES #Print the first element of the list. !!PLEASE NOTE THIS PRINTS A DICTIONARY BECAUSE EACH ELEMENT IS ITS OWN DICTIONARY!! print(our_profiles[0]) #Print "_______ is ______ years old and loves _______ ice cream" for the second person in the group. print(our_profiles[1]["name"] + " is " + our_profiles[1]["age"] + " years old and loves " + our_profiles[1][fav_ice_cream] + " ice cream.") ##Update our List #Change the second person's age to 100. our_profiles[1]["age"] = 100 #Add a new person to our group (Ellie, 22, 09/04/1996, Chocolate Fudge Brownie) our_profiles.append({"name": "Ellie", "age": 22, "birthday": "09/04/1996", "fav_ice_cream": "Chocolate Fudge Brownie"}) ##Iterate over the list of DICTIONARIES #Create a list called our_birthdays of our birthdays. our_birthdays = [] for person in our_profiles: our_birthdays.append(person["birthday"]) #Print a statment for each person that says: "_______'s birthday is _______ and they are currently ______ years old." for person in our_profiles: print(person["name"] + "'s birthday is " + person["birthday"] + " and they are currently " + person["age"] + " years old.")
#变量作用域 def func(num1): num2=30 #python会在局部中复制全局变量,自动创建内部用 print(num1) print(num2) num2=20 func(10) print(num2);
#删除链表中的节点 #请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。 #现有一个链表 -- head = [4,5,1,9],它可以表示为: # 4 -> 5 -> 1 -> 9 class Solution: def deleteNode(self, node): node.val=node.next.val#当前值被后一个值覆盖 node.next=node.next.next#下一节点跳到下下一节点
# 有效的字母异位词 #给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。 #示例 1: #输入: s = "anagram", t = "nagaram" #输出: true #示例 2: #输入: s = "rat", t = "car" #输出: false #说明: #你可以假设字符串只包含小写字母。 #进阶: #如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况? import collections class Solution: def isAnagram(self, s, t): if len(s) == len(t): dict = collections.Counter(s) dict2 = collections.Counter(t) num=0 for k,v in dict.items(): print(k,v) if k in dict2 and v == dict2[k]: num+=1 #if num==len(dict): # return True #else # return False return True if num==len(dict) else False else: return False print(isAnagram(1,'abc','acb'))
def ds(x): return 2*x+1 lambda x:2*x+1 g=lambda x,y:x+y print(g(3,4)) #内置函数filter过滤器,去掉非True的 print('=================') def odd(x): return x%2 temp = range(10) show = filter(odd,temp) print(list(show)) print(list(filter(lambda x : x%2,range(10)))) print(list(range(10))) print('=================') #内置函数map print(list(map(lambda x:x*2,range(10))))
import random ## This is guess the number game print('Hello !!! What is your name ???') name = input() secnum = random.randint(1,20) print('Well,'+ name + ' ....I am thinking of number between 1 - 20') ##This is allowing user to guess the number (max guess --> 6) print('You have six guesses !!!') for i in range (1,7): num = int(input('Enter the number !!!')) if num > secnum: print('It is too high') elif num <secnum: print('It is too low ') else: break ##Checking whether he won or lost if i<=6: print('WOOOOOOH !!!!You won ..!!!You took '+str(i)+' guesses') else: print('You 1ost ')
from scipy import misc def chebyshev(x0,count): x1=x0-(f(x0)/fprime(x0))+(1/2)*((f(x0)**2)*fdprime(x0))/(fprime(x0))**3 print('f(x1),f(x0):{},{} and x1,x0:{},{}'.format(f(x1),f(x0),x1,x0)) count+=1 print('In the {} iteration, value of x{} is {}'.format(count,count,x1)) if f(x1)==0: print('Breaking out f({}) equals zero'.format(x1)) return x1 elif abs(x1-x0)<0.0001: print('Breaking out, {}-{} is less than 0.0001'.format(x1,x0)) return x1 elif count>=15: print('Exiting') return x1 else: return chebyshev(x1,count) def f(x): return x**3-4*x-9 def fdprime(j): return misc.derivative(f,j,n=2) def fprime(j): return misc.derivative(f,j,n=1) def initial_approx(upper,lower): if abs(f(upper))<abs(f(lower)): return upper else: return lower def main(): upper=3 lower=2 count=0 initial=initial_approx(upper,lower) print(initial) root=chebyshev(initial,count) if __name__ == '__main__': main()
grade1 = float(input("Type the grade of the first test: ")) grade2 = float(input("Type the grade of the second test: ")) abscenes = int(input("Type the number of abscenes: ")) total_classes = int(input("Type the total number of classes: ")) avg_grade = (grade1 + grade2) / 2 attendance = (total_classes - abscenes) / total_classes print("Average grade: ", round(avg_grade,2)) print("Attendance rate: ", str(round((attendance * 100),2))+ '%') if (avg_grade >= 6): if (attendance >= 0.8): print("The student has been approved.") else: print("The student has failed due to an attendance rate lower than 80%.") elif (attendance >= 0.8): print("The student has failed due to an average grade lower than 6.0.") else: print("The student has failed due to an average grade lower than 6.0 and an attendance rate lower than 80%.")
def say_hello(): print("Hello!") def say_hello_arguments(person1, person2): print("Hello " + person1 + ", how are you doing? " + person2 + " is waiting for you.") def fahrTocelsius(fahr): celsius = (5 * (fahr - 32)) / 9 return celsius say_hello() person1 = "Marcia" person2 = "Luciano" say_hello_arguments(person1, person2) print("Celsius: ", round(fahrTocelsius(100),2)) print("Kelvin: ", round(fahrTocelsius(100) + 273.5 ,2) )
ALPHABET = (('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'), ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z')) def content_to_str(data_file_name): """Creates string with content from file""" content = [] with open(data_file_name, 'r') as f: content = f.read() return content def print_decoded(i, n): poz = ALPHABET[n].index(i) + 1 print(ALPHABET[n][-poz], end='') def main(): word = content_to_str('text.txt') for i in word: if i == '\n': print('') elif i == " ": print(' ', end='') elif i in ALPHABET[0]: print_decoded(i, 0) elif i in ALPHABET[1]: print_decoded(i, 1) if __name__ == '__main__': main()
#source file is from #http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python ''' This program should list out the serial port names to figure out what are the port names used to connect to mac (darwin), linux and windows. port names are needed to connnect to bluetooth device, as once paired it is through a serial device (linux) or com port (windows) how to detect the platform python is running on is also demonstrated. we could possibly just hardcode the ports when we know what they are called on each machine for simplicity. ''' import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): print ('Windows detected -- takes a moment') # one of the ports must be the right one if this works. I can't test don't have windows computer with bluetooth. ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): print ('Linux detected -- takes a moment') # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/tty[A-Za-z]*') elif sys.platform.startswith('darwin'): print ('MAC detected-- takes a moment') ports = glob.glob('/dev/tty.*') #ls /dev/tty.* on command line to see the same values else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports())
""" Can you check to see if a string has the same amount of 'x's and 'o's? Eg: XO("ooxx") => true XO("xooxx") => false XO("ooxXm") => true XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true XO("zzoo") => false Note: The method must return a boolean and be case insensitive. The string can contain any character """ def count_chr(s): x_count = s.lower().count('x') o_count = s.lower().count('o') if x_count == o_count: return True else: return False print(count_chr('xOoxx')) print(count_chr('zpzpzpp'))
""" Your goal is to create a function that removes the first and last letters of a string. Strings with two characters or less are considered invalid. You can choose to have your function return null or simply ignore. """ def solution(somestr): if len(somestr) > 2: return somestr[1:-1] return None def goingwild(somestr): if len(somestr) > 2: temp = list(somestr) temp.pop() temp.reverse() temp.pop() temp.reverse() return ''.join(temp) return None if __name__ == "__main__": # my testcases print(solution('hello whatsup?')) # ello whatsup print(solution('d4')) # None print(goingwild('hello whatsup?')) # ello whatsup
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 """ def reverse_dig(num): num = str(num) if num.startswith('-'): return int('-'+num.split('-')[1][::-1]) else: return int(num[::-1]) print(reverse_dig(123)) print(reverse_dig(-321)) print(reverse_dig(100))
import math def normalize_angle(p): if p > 180: return p - 360 if p < - 180: return p + 360 else: return p theta = 0 target = int(raw_input("target>")) error = target - theta a_error = abs(error) if a_error >= 90: error = normalize_angle(180 - error) a_error = abs(error) v_sign = -1.0 else: v_sign = 1.0 if error < 0: w_sign = -1.0 else: w_sign = 1.0 print error if -v_sign*w_sign > 0: print "CW", else: print "CCW", if v_sign < 0: print "REV" else: print "FWD"
############################################################################### # Computer Project #8 # # Algorithm # prompt for a file containing hurricane information # form a dictionary using the names, years, and data of the hurricane # update the dictionary for every name & year found # organize the hurricane information to be added in a table,graph # Add the information in a table # Graph the trajectory of the hurricanes # Plot the information in a graph according to wind speed # Call all the functions in a main function # Return the requested information ############################################################################### import pylab as py from operator import itemgetter def open_file(): ''' Opens a file input by the user. Reprompts if the entered file name is invalid Returns the entered file name for reading (fp) ''' while True: try: #try to open an input file for reading filename = input("Input a file name: ") fp = open(filename,"r") return fp except: #if the file isn't found, print an error message and reprompt print("Unable to open file. Please try again.") def tryfloat(x): ''' Converts values to floats if they're a number, otherwise the value is 0. x: value being converted returns the converted value (a) ''' try: #convert it to a float a = float(x) #if the variable doesn't have digits in it except: #the variable is 0 a = 0 return a def update_dictionary(dictionary, year, hurricane, data): ''' Updates all the hurricane information contained in a dictionary. dictionary: dictionary where the years are stored. year: A key in the dictionary hurricane: a second key for the dictionary data: The hurricane data which is a value for the hurricanes ''' hurricane_dict = {} #check if year is in the dictionary if year not in dictionary: #if not, create an empty dictionary for the year dictionary[year] = hurricane_dict #check if hurricane is in dictionary[year] if hurricane not in dictionary[year]: #if not, create an empty list for that hurricane & year dictionary[year][hurricane] = [] #append the data to the list inside the dictionary[year][hurricane] dictionary[year][hurricane].append(data) def create_dictionary(fp): ''' Takes the data provided by the file being read then adds it to a tuple. fp: file pointer being read Returns a dictionary with all the hurricane information(dictionary) ''' #create an empty dictionary dictionary = {} #read the file for line in fp: line = line.split() year = line[0] hurricane = line[1] lat = float(line[3]) lon = float(line[4]) date = line[5] wind = tryfloat(line[6]) pressure = tryfloat(line[7]) data = (lat,lon,date,wind,pressure) update_dictionary(dictionary,year,hurricane,data) return dictionary def display_table(dictionary, year): ''' Displays an alphabetical list of hurricane names. dictionary: the dictionary of hurricanes being iterated through year: The keys of the dictionary ''' #create a list of the sorted hurricane names print("{:^70s}".format("Peak Wind Speed for the Hurricanes in " + year)) print("{:15s}{:>15s}{:>20s}{:>15s}".format("Name","Coordinates",\ "Wind Speed (knots)","Date")) hurricane_names = sorted(dictionary[year].keys()) #iterate through the list of hurricanes for hurricane in hurricane_names: #get a sorted list of points in descending order list_to_sort = dictionary[year][hurricane] points = sorted(list_to_sort, key = itemgetter(3,0,1),reverse = True) max_points = points[0] print("{:15s}({:6.2f},{:6.2f}){:>20.2f}{:>15s}".format\ (hurricane,max_points[0],max_points[1],max_points[3],max_points[2])) def get_years(dictionary): ''' Finds the oldest and most recent years in a dictioanry dictioanry: the dictionary with the hurricane names & corresponding years returns a tuple with the oldest year & the most recent year(tup) ''' #sort the dictionary in chronological order years_list = sorted(dictionary) min_year = years_list[0] max_year = years_list[-1] #add the lowest and highest years to a tuple tup = (min_year, max_year) return tup def prepare_plot(dictionary, year): ''' Makes a graph of hurricanes according to their maximum wind speeds dictionary: the dictionary containing the hurricane data year: the year the hurricane occured. returns a tuple of hurricane names,coordinates, and maximum wind speeds. ''' #get the list of sorted hurricane names hurricane_names = sorted(dictionary[year].keys()) #create empty lists of coordinates and max_speeds coordinates = [] max_wind_speed = [] #iterate through the list of hurricane names for hurricane in hurricane_names: data_list_tuples = dictionary[year][hurricane] #create empty lists of coordinates and wind speeds cord = [] wind_speed = [] #iterate through the list of tuples(dictionary values) for tup in data_list_tuples: #add the lattitude and longitude to the temporary coordinates list cord.append((tup[0],tup[1])) #add the wind speed to the wind_speed list wind_speed.append(tup[3]) #sort the wind_speeds in ascending order wind_sorted = sorted(wind_speed) #add the cordinates to the coordinates list coordinates.append(cord) #add the maximum wind speed to the max_wind_speed list max_wind_speed.append(wind_sorted[-1]) #return the hurricane names, coordinates, and maximum wind speed. return(hurricane_names,coordinates,max_wind_speed) def plot_map(year, size, names, coordinates): ''' Receives the year,category,hurricane names, and coordinates. Plots them on a graph. year: Year the hurricane occured size: Category of the hurricane names: names of the hurricane coordinates: longitude and lattitude of the coordinates ''' # The the RGB list of the background image img = py.imread("world-map.jpg") # Set the max values for the latitude and longitude of the map max_longitude, max_latitude = 180, 90 # Set the background image on the plot py.imshow(img,extent=[-max_longitude,max_longitude,\ -max_latitude,max_latitude]) # Set the corners of the map to cover the Atlantic Region xshift = (50,190) yshift = (90,30) # Show the atlantic ocean region py.xlim((-max_longitude+xshift[0],max_longitude-xshift[1])) py.ylim((-max_latitude+yshift[0],max_latitude-yshift[1])) # Generate the colormap and select the colors for each hurricane cmap = py.get_cmap('gnuplot') colors = [cmap(i/size) for i in range(size)] # plot each hurricane's trajectory for i,key in enumerate(names): lat = [ lat for lat,lon in coordinates[i] ] lon = [ lon for lat,lon in coordinates[i] ] py.plot(lon,lat,color=colors[i],label=key) # Set the legend at the bottom of the plot py.legend(bbox_to_anchor=(0.,-0.5,1.,0.102),loc=0, ncol=3,mode='expand',\ borderaxespad=0., fontsize=10) # Set the labels and titles of the plot py.xlabel("Longitude (degrees)") py.ylabel("Latitude (degrees)") py.title("Hurricane Trayectories for {}".format(year)) py.show() # show the full map def plot_wind_chart(year,size,names,max_speed): ''' Gets the year,size,name,and maximum speed of the hurricanes. Plots their Routes. year: Year the hurricane occured. size: Category of the hurricane. names: Name of the hurricane. max_speed: maximum speed of the hurricane ''' # Set the value of the category cat_limit = [ [v for i in range(size)] for v in [64,83,96,113,137] ] # Colors for the category plots COLORS = ["g","b","y","m","r"] # Plot the Wind Speed of Hurricane for i in range(5): py.plot(range(size),cat_limit[i],COLORS[i],label="category-{:d}".format(i+1)) # Set the legend for the categories py.legend(bbox_to_anchor=(1.05, 1.),loc=2,\ borderaxespad=0., fontsize=10) py.xticks(range(size),names,rotation='vertical') # Set the x-axis to be the names py.ylim(0,180) # Set the limit of the wind speed # Set the axis labels and title py.ylabel("Wind Speed (knots)") py.xlabel("Hurricane Name") py.title("Max Hurricane Wind Speed for {}".format(year)) py.plot(range(size),max_speed) # plot the wind speed plot py.show() # Show the plot def main(): ''' Prints information for a specific hurricane by calling all the functions. ''' #open the file for reading fp = open_file() #create a dictionary by iterating through the file pointer dictionary = create_dictionary(fp) #find the range of years (min_year,max_year) = get_years(dictionary) print("Hurricane Record Software") print("Records from {:4s} to {:4s}".format(min_year, max_year)) #prompt the user for a year that the hurricane occured hurricane_year = input("Enter the year to show hurricane data or 'quit': ") hurricane_year = hurricane_year.lower() while hurricane_year !="quit": #if the year entered is a number from 2007-2017, display the table. if hurricane_year.isdigit() == True and \ int(max_year)>= int(hurricane_year) >= int(min_year): display_table(dictionary,hurricane_year) #ask the user if they want to plot plot = input("\nDo you want to plot? ") if plot.lower() == "yes": #organize the names, coordinates, and speeds of the hurricanes names, coordinates, max_speed = prepare_plot(dictionary,hurricane_year) size = len(max_speed) #make a diagram of hurricane trajectories plot_map(hurricane_year, size, names, coordinates) #make a graph of wind_speeds plot_wind_chart(hurricane_year, size, names, max_speed) else: #if the year isn't an integer between 2007-2017, reprompt. print("Error with the year key! Try another year") hurricane_year = input("Enter the year to show hurricane data or 'quit': ") hurricane_year = hurricane_year.lower() if __name__ == "__main__": main()
# find the largest number in an array def find_largest(alist): if len(alist) == 1: return alist[0] elif alist[0]>find_largest(alist[1:]): return alist[0] else: return find_largest(alist[1:]) list = [5, 1, 8, 7, 2] print(find_largest(list))
class Day1: def __init__(self): self.inputs = [] with open("inputs/1.txt") as f: for line in f: self.inputs.append(int(line.strip())) def part1(self): seen_nums = set() for num in self.inputs: if (2020 - num) in seen_nums: return (2020 - num) * num seen_nums.add(num) def part2(self): seen_nums = set() known_sums = {} # sum of 2 numbers: what the 2 numbers are for num in self.inputs: known_sum_nums = known_sums.get(2020 - num) if known_sum_nums: return num * known_sum_nums[0] * known_sum_nums[1] seen_nums.add(num) for seen_num in seen_nums: known_sums[num + seen_num] = (num, seen_num) problem = Day1() print(problem.part1()) print(problem.part2())
#!/usr/bin/env python import sys sys.path.append( '../' ) from rtfng import * SAMPLE_PARA = """The play opens one year after the death of Richard II, and King Henry is making plans for a crusade to the Holy Land to cleanse himself of the guilt he feels over the usurpation of Richard's crown. But the crusade must be postponed when Henry learns that Welsh rebels, led by Owen Glendower, have defeated and captured Mortimer. Although the brave Henry Percy, nicknamed Hotspur, has quashed much of the uprising, there is still much trouble in Scotland. King Henry has a deep admiration for Hotspur and he longs for his own son, Prince Hal, to display some of Hotspur's noble qualities. Hal is more comfortable in a tavern than on the battlefield, and he spends his days carousing with riff-raff in London. But King Henry also has his problems with the headstrong Hotspur, who refuses to turn over his prisoners to the state as he has been so ordered. Westmoreland tells King Henry that Hotspur has many of the traits of his uncle, Thomas Percy, the Earl of Worcester, and defying authority runs in the family.""" def MakeExample1() : doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append( section ) # text can be added directly to the section # a paragraph object is create as needed section.append( 'Example 1' ) # blank paragraphs are just empty strings section.append( '' ) # a lot of useful documents can be created # with little more than this section.append( 'A lot of useful documents can be created ' 'in this way, more advance formating is available ' 'but a lot of users just want to see their data come out ' 'in something other than a text file.' ) return doc def MakeExample2() : doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append( section ) # things really only get interesting after you # start to use styles to spice things up p = Paragraph( ss.ParagraphStyles.Heading1 ) p.append( 'Example 2' ) section.append( p ) p = Paragraph( ss.ParagraphStyles.Normal ) p.append( 'In this case we have used a two styles. ' 'The first paragraph is marked with the Heading1 style so that it ' 'will appear differently to the user. ') section.append( p ) p = Paragraph() p.append( 'Notice that after I have changed the style of the paragraph ' 'all subsequent paragraphs have that style automatically. ' 'This saves typing and is the default behaviour for RTF documents.' ) section.append( p ) p = Paragraph() p.append( 'I also happen to like Arial so our base style is Arial not Times New Roman.' ) section.append( p ) p = Paragraph() p.append( 'It is also possible to provide overrides for element of a style. ', 'For example I can change just the font ', TEXT( 'size', size=48 ), ' or ', TEXT( 'typeface', font=ss.Fonts.Impact ) , '.' ) section.append( p ) p = Paragraph() p.append( 'The paragraph itself can also be overridden in lots of ways, tabs, ' 'borders, alignment, etc can all be modified either in the style or as an ' 'override during the creation of the paragraph. ' 'The next paragraph demonstrates custom tab widths and embedded ' 'carriage returns, ie new line markers that do not cause a paragraph break.' ) section.append( p ) # ParagraphPropertySet is an alias for ParagraphPropertySet para_props = ParagraphPropertySet( tabs = [ TabPropertySet( width=TabPropertySet.DEFAULT_WIDTH ), TabPropertySet( width=TabPropertySet.DEFAULT_WIDTH * 2 ), TabPropertySet( width=TabPropertySet.DEFAULT_WIDTH ) ] ) p = Paragraph( ss.ParagraphStyles.Normal, para_props ) p.append( 'Left Word', TAB, 'Middle Word', TAB, 'Right Word', LINE, 'Left Word', TAB, 'Middle Word', TAB, 'Right Word' ) section.append( p ) section.append( 'The alignment of tabs and style can also be controlled. ' 'The following paragraph demonstrates how to use flush right tabs' 'and leader dots.' ) para_props = ParagraphPropertySet( tabs = [ TabPropertySet( section.TwipsToRightMargin(), alignment = TabPropertySet.RIGHT, leader = TabPropertySet.DOTS ) ] ) p = Paragraph( ss.ParagraphStyles.Normal, para_props ) p.append( 'Before Dots', TAB, 'After Dots' ) section.append( p ) section.append( 'Paragraphs can also be indented, the following is all at the ' 'same indent level and the one after it has the first line ' 'at a different indent to the rest. The third has the ' 'first line going in the other direction and is also separated ' 'by a page break. Note that the ' 'FirstLineIndent is defined as being the difference from the LeftIndent.' ) section.append( 'The following text was copied from http://www.shakespeare-online.com/plots/1kh4ps.html.' ) para_props = ParagraphPropertySet() para_props.SetLeftIndent( TabPropertySet.DEFAULT_WIDTH * 3 ) p = Paragraph( ss.ParagraphStyles.Normal, para_props ) p.append( SAMPLE_PARA ) section.append( p ) para_props = ParagraphPropertySet() para_props.SetFirstLineIndent( TabPropertySet.DEFAULT_WIDTH * -2 ) para_props.SetLeftIndent( TabPropertySet.DEFAULT_WIDTH * 3 ) p = Paragraph( ss.ParagraphStyles.Normal, para_props ) p.append( SAMPLE_PARA ) section.append( p ) # do a page para_props = ParagraphPropertySet() para_props.SetPageBreakBefore( True ) para_props.SetFirstLineIndent( TabPropertySet.DEFAULT_WIDTH ) para_props.SetLeftIndent( TabPropertySet.DEFAULT_WIDTH ) p = Paragraph( ss.ParagraphStyles.Normal, para_props ) p.append( SAMPLE_PARA ) section.append( p ) return doc def MakeExample3() : doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append( section ) p = Paragraph( ss.ParagraphStyles.Heading1 ) p.append( 'Example 3' ) section.append( p ) # changes what is now the default style of Heading1 back to Normal p = Paragraph( ss.ParagraphStyles.Normal ) p.append( 'Example 3 demonstrates tables, tables represent one of the ' 'harder things to control in RTF as they offer alot of ' 'flexibility in formatting and layout.' ) section.append( p ) section.append( 'Table columns are specified in widths, the following example ' 'consists of a table with 3 columns, the first column is ' '7 tab widths wide, the next two are 3 tab widths wide. ' 'The widths chosen are arbitrary, they do not have to be ' 'multiples of tab widths.' ) table = Table( TabPropertySet.DEFAULT_WIDTH * 7, TabPropertySet.DEFAULT_WIDTH * 3, TabPropertySet.DEFAULT_WIDTH * 3 ) c1 = Cell( Paragraph( 'Row One, Cell One' ) ) c2 = Cell( Paragraph( 'Row One, Cell Two' ) ) c3 = Cell( Paragraph( 'Row One, Cell Three' ) ) table.AddRow( c1, c2, c3 ) c1 = Cell( Paragraph( ss.ParagraphStyles.Heading2, 'Heading2 Style' ) ) c2 = Cell( Paragraph( ss.ParagraphStyles.Normal, 'Back to Normal Style' ) ) c3 = Cell( Paragraph( 'More Normal Style' ) ) table.AddRow( c1, c2, c3 ) c1 = Cell( Paragraph( ss.ParagraphStyles.Heading2, 'Heading2 Style' ) ) c2 = Cell( Paragraph( ss.ParagraphStyles.Normal, 'Back to Normal Style' ) ) c3 = Cell( Paragraph( 'More Normal Style' ) ) table.AddRow( c1, c2, c3 ) section.append( table ) section.append( 'Different frames can also be specified for each cell in the table ' 'and each frame can have a different width and style for each border.' ) thin_edge = BorderPropertySet( width=20, style=BorderPropertySet.SINGLE ) thick_edge = BorderPropertySet( width=80, style=BorderPropertySet.SINGLE ) thin_frame = FramePropertySet( thin_edge, thin_edge, thin_edge, thin_edge ) thick_frame = FramePropertySet( thick_edge, thick_edge, thick_edge, thick_edge ) mixed_frame = FramePropertySet( thin_edge, thick_edge, thin_edge, thick_edge ) table = Table( TabPropertySet.DEFAULT_WIDTH * 3, TabPropertySet.DEFAULT_WIDTH * 3, TabPropertySet.DEFAULT_WIDTH * 3 ) c1 = Cell( Paragraph( 'R1C1' ), thin_frame ) c2 = Cell( Paragraph( 'R1C2' ) ) c3 = Cell( Paragraph( 'R1C3' ), thick_frame ) table.AddRow( c1, c2, c3 ) c1 = Cell( Paragraph( 'R2C1' ) ) c2 = Cell( Paragraph( 'R2C2' ) ) c3 = Cell( Paragraph( 'R2C3' ) ) table.AddRow( c1, c2, c3 ) c1 = Cell( Paragraph( 'R3C1' ), mixed_frame ) c2 = Cell( Paragraph( 'R3C2' ) ) c3 = Cell( Paragraph( 'R3C3' ), mixed_frame ) table.AddRow( c1, c2, c3 ) section.append( table ) section.append( 'In fact frames can be applied to paragraphs too, not just cells.' ) p = Paragraph( ss.ParagraphStyles.Normal, thin_frame ) p.append( 'This whole paragraph is in a frame.' ) section.append( p ) return doc def MakeExample4() : doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append( section ) section.append( 'Example 4' ) section.append( 'This example test changing the colour of fonts.' ) # # text properties can be specified in two ways, either a # Text object can have its text properties specified like: tps = TextPropertySet( colour=ss.Colours.Red ) text = Text( 'RED', tps ) p = Paragraph() p.append( 'This next word should be in ', text ) section.append( p ) # or the shortcut TEXT function can be used like: p = Paragraph() p.append( 'This next word should be in ', TEXT( 'Green', colour=ss.Colours.Green ) ) section.append( p ) # when specifying colours it is important to use the colours from the # style sheet supplied with the document and not the StandardColours object # each document get its own copy of the stylesheet so that changes can be # made on a document by document basis without mucking up other documents # that might be based on the same basic stylesheet return doc # # DO SOME WITH HEADERS AND FOOTERS def MakeExample5() : doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append( section ) section.Header.append( 'This is the header' ) section.Footer.append( 'This is the footer' ) p = Paragraph( ss.ParagraphStyles.Heading1 ) p.append( 'Example 5' ) section.append( p ) # blank paragraphs are just empty strings section.append( '' ) p = Paragraph( ss.ParagraphStyles.Normal ) p.append( 'This document has a header and a footer.' ) section.append( p ) return doc def MakeExample6() : doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append( section ) section.FirstHeader.append( 'This is the header for the first page.' ) section.FirstFooter.append( 'This is the footer for the first page.' ) section.Header.append( 'This is the header that will appear on subsequent pages.' ) section.Footer.append( 'This is the footer that will appear on subsequent pages.' ) p = Paragraph( ss.ParagraphStyles.Heading1 ) p.append( 'Example 6' ) section.append( p ) # blank paragraphs are just empty strings section.append( '' ) p = Paragraph( ss.ParagraphStyles.Normal ) p.append( 'This document has different headers and footers for the first and then subsequent pages. ' 'If you insert a page break you should see a different header and footer.' ) section.append( p ) return doc def MakeExample7() : doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append( section ) section.FirstHeader.append( 'This is the header for the first page.' ) section.FirstFooter.append( 'This is the footer for the first page.' ) section.Header.append( 'This is the header that will appear on subsequent pages.' ) section.Footer.append( 'This is the footer that will appear on subsequent pages.' ) p = Paragraph( ss.ParagraphStyles.Heading1 ) p.append( 'Example 7' ) section.append( p ) p = Paragraph( ss.ParagraphStyles.Normal ) p.append( 'This document has different headers and footers for the first and then subsequent pages. ' 'If you insert a page break you should see a different header and footer.' ) section.append( p ) p = Paragraph( ss.ParagraphStyles.Normal, ParagraphPropertySet().SetPageBreakBefore( True ) ) p.append( 'This should be page 2 ' 'with the subsequent headers and footers.' ) section.append( p ) section = Section( break_type=Section.PAGE, first_page_number=1 ) doc.Sections.append( section ) section.FirstHeader.append( 'This is the header for the first page of the second section.' ) section.FirstFooter.append( 'This is the footer for the first page of the second section.' ) section.Header.append( 'This is the header that will appear on subsequent pages for the second section.' ) p = Paragraph( 'This is the footer that will appear on subsequent pages for the second section.', LINE ) p.append( PAGE_NUMBER, ' of ', SECTION_PAGES ) section.Footer.append( p ) section.append( 'This is the first page' ) p = Paragraph( ParagraphPropertySet().SetPageBreakBefore( True ), 'This is the second page' ) section.append( p ) return doc def OpenFile( name ) : return file( '%s.rtf' % name, 'w' ) if __name__ == '__main__' : DR = Renderer() doc1 = MakeExample1() doc2 = MakeExample2() doc3 = MakeExample3() doc4 = MakeExample4() doc5 = MakeExample5() doc6 = MakeExample6() doc7 = MakeExample7() DR.Write( doc1, OpenFile( '1' ) ) DR.Write( doc2, OpenFile( '2' ) ) DR.Write( doc3, OpenFile( '3' ) ) DR.Write( doc4, OpenFile( '4' ) ) DR.Write( doc5, OpenFile( '5' ) ) DR.Write( doc6, OpenFile( '6' ) ) DR.Write( doc7, OpenFile( '7' ) ) print "Finished"
import random def r11_is_multiple(n: int,m: int): return n/m == int(n/m) def r12_is_even(k): return divmod(k,2)[1] == 0 def r13_minmax(data): sorteddata = sorted(data) return (sorteddata[0],sorteddata[-1]) def sq_of_num(num): return num ** 2 def r14_sq_less_n(n): sumOfSquares = 0 while n != 0: sumOfSquares = sumOfSquares + sq_of_num(n) n -= 1 return sumOfSquares def r112_my_choice(data): return data[random.randrange(0,len(data))] print(r11_is_multiple(10,4)) print(r12_is_even(12)) print(r13_minmax([3,1,5,2])) print(r14_sq_less_n(4)) print(sum([x**2 for x in range(1,4+1)])) # ex_r_1_7 print([x**2 for x in range(10)][8]) # ex_r_1_8 ans: -k j = n-k print([x for x in range(50,90,10)]) # ex_r_1_9 print([x for x in range(8,-10,-2)]) # ex_r_1_10 print([2 ** x for x in range(0,9)]) # ex_r_1_11 print([r112_my_choice([2 ** x for x in range(0,9)])])
class Point: """Represents a point in a 2 dimensional space """ def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return '(' + str(self.x) + ', ' + str(self.y) + ')' def __add__(self, self1): return Point(self.x + self1.x, self.y + self1.y) def increment(self, x, y): self.x += x self.y += y return self.x, self.y points = Point(5, 7) points1 = Point(3, 4) points.increment(0, 5) points2 = points + points1 print points2
import numpy as np def load_data(mode='train'): """ Function to (download and) load the MNIST data :param mode: train or test :return: images and the corresponding labels """ from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) if mode == 'train': x_train, y_train, x_valid, y_valid = mnist.train.images, mnist.train.labels, \ mnist.validation.images, mnist.validation.labels return x_train, y_train, x_valid, y_valid elif mode == 'test': x_test, y_test = mnist.test.images, mnist.test.labels return x_test, y_test def randomize(x, y): """ Randomizes the order of data samples and their corresponding labels""" permutation = np.random.permutation(y.shape[0]) shuffled_x = x[permutation, :] shuffled_y = y[permutation] return shuffled_x, shuffled_y def reformat(x, y): """ Reformats the data to the format acceptable for convolutional layers :param x: input array :param y: corresponding labels :return: reshaped input and labels """ img_size, num_ch, num_class = int(np.sqrt(x.shape[-1])), 1, len(np.unique(np.argmax(y, 1))) dataset = x.reshape((-1, img_size, img_size, num_ch)).astype(np.float32) labels = (np.arange(num_class) == y[:, None]).astype(np.float32) return dataset, labels def get_next_batch(x, y, start, end): x_batch = x[start:end] y_batch = y[start:end] return x_batch, y_batch
import tensorflow as tf import numpy as np # Create input data # Lets say you have a batch of two examples, one is of length 10, and the other of length 6. # Each one is a vector of 8 numbers (time-steps=8) X = np.random.randn(2, 10, 8) # [batch_size, max_time (or length), input_dim] # The second example is of length 6 X[1, 6:] = 0 X_lengths = [10, 6] cell = tf.nn.rnn_cell.LSTMCell(num_units=100) outputs, last_states = tf.nn.dynamic_rnn(cell, X, sequence_length=X_lengths, dtype=tf.float64) # X: input of shape [batch_size, max_time, input_dim] # sequence_length: (optional) An int32/int64 vector sized `[batch_size]`. Used to copy-through # state and zero-out outputs when past a batch element's sequence length. So it's more for # correctness than performance. # dtype: (optional) The data type for the initial state and expected output. # (If there is no initial_state, you must give a dtype.) # outputs: [batch_size, max_time, num_hidden_units] (=ht) # last_states: the last state for each example (cT, hT), each of shape [batch_size, num_hidden_units] # If cells are `LSTMCells`, `state` will be a tuple containing a `LSTMStateTuple` for each cell. print()
import numpy as np def loss_surface(model_parameters, target_weights, target_ix, model, y): """ Function to return the cost surface between two chosen weights in a model and its L2 loss surface. Parameters ---------- model_parameters: tuple containing the parameters to compute the model target_weights: tuple of lenght 2 containing the parameters compute the loss target_ix: typle of lenght 2 containing the indices for each parameter to compute the loss model: function with parameters "model_parameters" used to compute the output of the model y: vector with m model outputs Returns ------- tuppple with grid containing the surface along the chosen parameters """ # target weights tweight1, tweight2 = target_weights # target indices tix1, tix2 = target_ix # Grid surface for target weights to plot tw1, tw2 = np.mgrid[-5:5:0.1, -5:5:0.1] # Initialize cost surface J = np.zeros_like(tw1.ravel()) for ix, (tw1i, tw2i) in enumerate(zip(tw1.ravel(), tw2.ravel())): tweight1[tix1] = tw1i tweight2[tix2] = tw2i yhat = model(*model_parameters) # Updating cost function try: J[ix] = np.sum((yhat - y) ** 2) / 2 except Exception: print(ix) J = J.reshape(*tw1.shape) return tw1, tw2, J
def quickSort(aArray): quickSortHelper(aArray, 0, len(aArray)-1) def quickSortHelper(aArray, first, last): if first < last: splitpoint = partition(aArray, first, last) quickSortHelper(aArray, first, splitpoint-1) quickSortHelper(aArray, splitpoint+1, last) def partition(aArray, first, last): pivotvalue = aArray[first] leftmark = first+1 rightmark = last done = False while not done: while leftmark <= rightmark and aArray[leftmark] <= pivotvalue: leftmark = leftmark + 1 while aArray[rightmark] >= pivotvalue and rightmark >= leftmark: rightmark = rightmark - 1 if rightmark < leftmark: done = True else: temp = aArray[leftmark] aArray[leftmark] = aArray[rightmark] aArray[rightmark] = temp temp = aArray[first] aArray[first] = aArray[rightmark] aArray[rightmark] = temp return rightmark
def champion_search(api,summoner_id,active=False): if not active: print 'This program is inactive' print 'Exiting...' return stat_ranked = api.get_stats_ranked(summoner_id) #won't work if you haven't played ranked before ranked_champions={} count=1 for champion in stat_ranked['champions']: if champion['id']==0: continue champion_info = api.get_champion_name(champion['id']) #find a way to get names off of champion.json ranked_champions[champion_info['name'].lower()]=champion['stats'] print 'Loading champion %d data...'.center(50) %(count) count+=1 while True: print '\n'+'-'*50 print 'Champions played:' for name in sorted(ranked_champions): print ' '*2+name.title() print answer=raw_input('Please enter a champion: ').lower() ##stops program if answer=='stop': print 'Exiting' return ##detects if the champion is in ranked_champions if answer not in ranked_champions: print '-'*50+'\n' print 'Invalid champion' continue ##can filter some of the champion's stats so that only desired ones are seen champ_filter=raw_input('Please enter a filter: ').lower().replace(' ','') valid=False ##Boolean set to see if given filter is in the possible stats for ranked champs for stat in ranked_champions[answer]: if champ_filter in stat.lower(): valid=True break if valid==False: print '-'*50+'\n' print 'Invalid filter' continue print '-'*50+'\n' print answer.title() for stat in sorted(ranked_champions[answer]): if champ_filter in stat.lower(): print stat.replace('total','').replace('most','')+':','{:,}'.format(ranked_champions[answer][stat]) print raw_input('Hit enter to continue...') if __name__=='__main__': from RiotAPI import RiotAPI api = RiotAPI('3029076c-24d5-4b04-93cc-eda77e5ab23f') summoner = raw_input('Enter Summoner Name: ').replace(' ','').lower() #print 'Retrieving data please wait...'.center(50) r = api.get_summoner_by_name(summoner) summoner_id = r[summoner]['id'] while True: champion_search(api,summoner_id,True) break
from tkinter import * root = Tk() root.title("simle calculator") e = Entry(root, width=60, borderwidth=5) e.grid(row=0, column=0, rowspan=2, columnspan=5, padx=10, pady=10) def button_click(number): current = e.get() global expr expr = str(current)+str(number) e.delete(0, END) e.insert(0, expr) def clr(): e.delete(0, END) def button_equal(): total = eval(expr) e.delete(0, END) e.insert(0, total) button1 = Button(root, text="1", padx=40, pady=20, command=lambda: button_click("1")) button2 = Button(root, text="2", padx=40, pady=20, command=lambda: button_click("2")) button3 = Button(root, text="3", padx=40, pady=20, command=lambda: button_click("3")) button4 = Button(root, text="4", padx=40, pady=20, command=lambda: button_click("4")) button5 = Button(root, text="5", padx=40, pady=20, command=lambda: button_click("5")) button6 = Button(root, text="6", padx=40, pady=20, command=lambda: button_click("6")) button7 = Button(root, text="7", padx=40, pady=20, command=lambda: button_click("7")) button8 = Button(root, text="8", padx=40, pady=20, command=lambda: button_click("8")) button9 = Button(root, text="9", padx=40, pady=20, command=lambda: button_click("9")) button0 = Button(root, text="0", padx=40, pady=20, command=lambda: button_click("0")) button_add = Button(root, text="+", padx=40, pady=20, command=lambda: button_click("+")) button_diff = Button(root, text="-", padx=40, pady=20, command=lambda: button_click("-")) button_multiply = Button(root, text="*", padx=40, pady=20, command=lambda: button_click("*")) button_div = Button(root, text="/", padx=40, pady=20, command=lambda: button_click("/")) button_equals = Button(root, text="=", padx=200, pady=20, command=button_equal) button_clear = Button(root, text="clear", padx=90, pady=20, command=clr) button1.grid(row=2, column=0) button2.grid(row=2, column=1) button3.grid(row=2, column=2) button4.grid(row=3, column=0) button5.grid(row=3, column=1) button6.grid(row=3, column=2) button7.grid(row=4, column=0) button8.grid(row=4, column=1) button9.grid(row=4, column=2) button0.grid(row=5, column=0) button_diff.grid(row=4, column=4) button_clear.grid(row=5, column=1, columnspan=2) button_equals.grid(row=6, column=0, columnspan=5) button_add.grid(row=5, column=4) button_div.grid(row=2, column=4) button_multiply.grid(row=3, column=4) root.mainloop()
## Accepts a list of numbers as an argument and returns the smallest number on list. number_list = [10, 4, 35340, -3, 16, 75, 82, 0] def smallest(list): ## Define function that returns smallest number. small_number = number_list[0] ## Must set intial check number to first number in list. ## Loop interate trough the list. for number in number_list: ## Check if current number is smaller than last small number (small_number). if number < small_number: ## If it is, assign current number to small_number. small_number = number return small_number print(f'\n{smallest(number_list)}\n')
#!/usr/bin/env python3 dic = { '\\' : b'\xe2\x95\x9a', '-' : b'\xe2\x95\x90', '/' : b'\xe2\x95\x9d', '|' : b'\xe2\x95\x91', '+' : b'\xe2\x95\x94', '%' : b'\xe2\x95\x97', } def decode(x): return (''.join(dic.get(i, i.encode('utf-8')).decode('utf-8') for i in x)) def input1(text): print(decode('+-------------%' + '+---------------%')) print(decode('| A) MUSHROOM |' + '| B) CHERRY PIE |')) print(decode('\\-------------/' + '\\---------------/')) answer = input('>>>') return(answer) def input2(text): print('What was that? Try again!') print(decode('+-----%' + '+----%')) print(decode('| A) |' + '| B) |')) print(decode('\\-----/' + '\\----/')) answer = input('>>>') return(answer) def input3(text): print('Yes or No?') print(decode('+-----%' + '+----%')) print(decode('| Yes |' + '| No |')) print(decode('\\-----/' + '\\----/')) answer = input('>>>') return(answer)
print('Common Multiples') def ismultiple(num_a, num_b):# Takes two numbers as arguement if num_b % num_a == 0: # if num_b divided by num_a returns a number with a remainer of 0 return True # return true else: return False # otherwise return false def commonmultiple(num_a, num_b, num_c): # takes three numbers as arguement if ismultiple(num_c, num_a) and ismultiple(num_c, num_b): # if num c is a multiple of both num_a and num_b return True # return true else: return False# otherwise return false num_1 = int(input('Enter first number: ')) # gets first integer input num_2 = int(input('Enter second number: '))# gets second integer input for x in range(1, 101): # checks for all numbers from 1 to 100 that are common multiples of both num_1 and num_2 if commonmultiple(num_1, num_2, x): print(x) # prints the numbers out if it returns true
print('Trip Distance Calculator') import math first_city = [0,0] second_city = [0,0] choice = "" distance = 0.0 first_city[0] = int(input('Enter x coordinate of first city: ')) first_city[1] = int(input('Enter y coordinate of first city: ')) while choice != 'q': second_city[0] = int(input('Enter x coordinate of next city: ')) second_city[1] = int(input('Enter y coordinate of next city: ')) distance += float(math.sqrt(((first_city[0] - second_city[0]) ** 2) + ((first_city[1] - second_city[1]) ** 2))) first_city[0] = second_city[0] first_city[1] = second_city[1] choice = input('''Would you like to keep calculating distances? Enter q to quit Enter anything else to continue: ''') print('Total distance travelled was ' + str(distance))
import random def create_sorted_list(range_of_nums): numslist = [] for x in range(range_of_nums): if random.randint(0,100) > 75: numslist.append(x) return numslist def create_unsorted_list(length, maxval): numslist = [] for x in range(length): numslist.append(random.randint(0,maxval)) return numslist def create_unique_list(length, maxval): numslist = [] for x in range(length): numslist.append(random.randint(0,maxval)) return numslist def create_2d_list(length, maxval): numslist = [] templist = [] for x in range(length): numslist.append([]) for y in range(2): numslist[x].append(random.randint(0, maxval)) return numslist print(create_unsorted_list(20, 80))
import listmaker def merge_lists(list1, list2, merged=[]): if len(list1) == 0: merged.extend(list2) return merged elif len(list2) == 0: merged.extend(list1) return merged if list1[0] <= list2[0]: merged.append(list1[0]) return merge_lists(list1[1:], list2, merged) elif list2[0] < list1[0]: merged.append(list2[0]) return merge_lists(list1, list2[1:], merged) print(merge_lists(listmaker.create_sorted_list(200), listmaker.create_sorted_list(200)))
print('Number of Digits') def numDigits(num): # takes a string as an arguement num = str(num) # converts string to integer value count = 0 # variable to hold the count of digits for x in num: # for every character in the num string count += 1 # increase count by 1 return count # return the count print(numDigits(14324324243243325650))
largest, smallest, average, total, positive, negative = 0,0,0,0,0,0 num = input('Enter an integer: ') if num == 'q': print('Largest number: ' + str(largest)) print('Smallest number: ' + str(smallest)) print('Average: ' + str(average)) print('Number of positives: ' + str(positive)) print('Number of negatives: ' + str(negative)) else: while not num.isdigit(): print('Invalid input') num = input('Enter an integer: ') while num != 'q': if num != 'q': num = int(num) total += 1 if total == 1: largest = num smallest = num else: if num > largest: largest = num elif num < smallest: smallest = num average += num if num > 0: positive += 1 elif num < 0: negative += 1 print('Number registered') num = input('Enter an integer: ') while not num.isdigit() and num != 'q': print('Invalid input') num = input('Enter an integer: ') if total > 0: print('---------------------------------') print('Largest number: ' + str(largest)) print('Smallest number: ' + str(smallest)) print('Average: ' + str(average/total)) print('Number of positives: ' + str(positive)) print('Number of negatives: ' + str(negative))
""" 14. mimic Neste desafio você vai fazer um gerador de lero-lero. É um programa que lê um arquivo, armazena a relação entre as palavras e então gera um novo texto respeitando essas relações para imitar um escritor de verdade. Para isso você precisa: A. Abrir o arquivo especificado via linha de comando. B. Ler o conteúdo e separar as palavras obtendo uma lista de palavras. C. Criar um dicionário de "imitação". Nesse dicionário a chave será uma palavra e o valor será uma lista contendo as palavras que aparecem no texto após a palavra usada na chave. Por exemplo, suponha um arquivo com o conteúdo: A B C B A O dicionário de imitação deve considerar que: * a chave A contém uma lista com a palavra B * a chave B contém uma lista com as palavras C e A * a chave C contém uma lista com a palavra B Além disso precisamos considerar que: * a chave '' contém uma lista com a primeira palavra do arquivo * a última palavra do arquivo contém uma lista com a palavra ''. Com o dicionario imitador é bastante simples emitir aleatoriamente texto que imita o original. Imprima uma palavra, depois veja quais palavras podem vir a seguir e pegue uma aleatoriamente como a proxima palavra do texto. Use a string vazia como a primeira palavra do texto para preparar as coisas. Nota: o módulo padrão do python 'random' conta com o random.choice(list), método que escolhe um elemento aleatório de uma lista não vazia. """ import random import sys def mimic_dict(filename): """Retorna o dicionario imitador mapeando cada palavra para a lista de palavras subsequentes.""" words = [] dictonary = {} with open(filename, "r") as fd: lines = fd.read().splitlines() for line in lines: for word in line.split(' '): words.append(word.lower()) dictonary[''] = words for key, word in enumerate(words): if word not in dictonary: dictonary.update({word: []}) if key >= len(words): dictonary[word].append('') elif words[key] not in dictonary[word]: dictonary[word].append(words[key]) else: continue return dictonary def print_mimic(mimic_dict, word): """Dado o dicionario imitador e a palavra inicial, imprime texto de 200 palavras.""" generate = [] for i in range(0, 200): generate.append(random.choice(mimic_dict[word])) print(''.join(generate)) # Chama mimic_dict() e print_mimic() def main(): if len(sys.argv) != 2: print('Utilização: ./14_mimic.py file-to-read') sys.exit(1) dict = mimic_dict(sys.argv[1]) print_mimic(dict, '') if __name__ == '__main__': main()
"""Utility module""" def list_to_dict(items: list) -> dict: """Transform a list to a dict with keys derived from indexes""" dict_values = {} for idx, value in enumerate(items): dict_values[idx] = value return dict_values
#!/usr/bin/env python import os #import numpy #import csv myfilename = "housing.data.txt" # if os.path.isfile(myfilename): # print("yay, I have a file") # if sky == blue: # print('yay the sky is blue') # else: # print ('boo, no files for me') with open(myfilename, 'r') as file_handle: housinglist = [] for line in file_handle.readlines(): line_clean = line.replace(' ', ' ').replace(' ', ' ') line_clean = line_clean.strip() values = line_clean.split(' ') caster = [] for value in values: if '.' in value: caster.append(float(value)) else: caster.append(int(value)) housinglist += [caster] print(housinglist[0:2]) #Just printing the first 2 rows print("End of list!!!. Now Converting Columns to Rows") rotated_list = [[housinglist[jdx][idx]for jdx, row in enumerate(housinglist)]for idx, column in enumerate(housinglist[0])] print(rotated_list[0]) #Just showing the first column rotated to row # for homework: # identify what type of data each value is, and cast it # to the appropriate type, then print the new, properly-typed # list to the screen. # I.e. ['0.04741', '0.00', '11.930', '0', '0.5730', '6.0300', '80.80', '2.5050', '1', '273.0', '21.00', '396.90', '7.88', '11.90'] # becomes: [0.04741, 0.0, 11.93, 0, 0.573, '6.03, 80.8, 2.505, 1, 273.0, 21.0, 396.90, 7.88, 11.90] print('finished! Homework 1 DONE')
import numpy as np import os import copy def basic_tokenized(): ''' Counts the number of unique words in a given input text And converts the text into sequences of numbers that correspond to words Arguments: (none) Return: word_dict - A list of words where the index corresponding to a word is its word index seqs_padded - A list of equal length lists where each sublist is a list of word indices representing a line of Shakespeare. Note: an index of -1 corresponds to end-padding ''' word_list = [] seqs = [] # Load data into sequences f = open('data/shakespeare.txt', 'r') #with os.path.join('data', 'shakespeare.txt') as f: for line in f: raw = line.strip().split() # Skip lines that aren't actually part of the Sonnets if len(raw) < 2: continue # If we encounter a new word for the first time, add it to word_list seqs.append([]) for word in raw: if word not in word_list: word_list.append(word) seqs[-1].append(word_list.index(word)) #f.close() # Create a list of words and their possible syllable counts f2 = open('data/Syllable_dictionary.txt', 'r') syllable_counts = {} for line in f2: raw = line.strip().split() #word_index = word_list.index(raw[0]) syllable_counts[raw[0]] = raw[1:] print('len(seqs)', len(seqs), seqs[0]) return word_list, seqs, syllable_counts def stripBadPunctuation(string): lst = ['(', ')'] string1 = '' for s in string: if s not in lst: string1 += s return string1 # we want to know if the last character is not punctuation, # indicates end with no punctuation def customStrip(string, punctuation): if string[-1] not in punctuation: return string + '#' return string # account for rhymes def advanced_tokenized(): ''' Counts the number of unique words in a given input text And converts the text into sequences of numbers that correspond to words Arguments: (none) Return: word_dict - A list of words where the index corresponding to a word is its word index seqs_padded - A list of equal length lists where each sublist is a list of word indices representing a line of Shakespeare. Note: an index of -1 corresponds to end-padding ''' punctuation = ['.', '!', ',', '?', ':', ';', '(', ')'] # not accounting for single quotes def ignore_punctuation(lst): return [i for i in lst if i >= len(punctuation)+1] # +1 because '#' added to end, stands for end w/o punctuation word_list = punctuation[:] word_list.append('#') seqs = [] list_rhymes = [] # list of lists, such that each list has rhymes # indices for the rhyme scheme that shakespeare uses: # abab, cdcd, efef, gg rhymeInd = [[0,2], [1,3], [4,6], [5,7], [8,10], [9,11], [12,13]] # Load data into sequences f = open('data/shakespeare.txt', 'r') countLine = 0 # count which line we are on for each sonnet lastWordsLst = [] # get the list of last words in each line # Keep track of the previous line for buffer prev = [] for line in f: #raw = stripBadPunctuation(line).strip().split() raw = customStrip(stripBadPunctuation(line), punctuation).split() # Skip lines that aren't actually part of the Sonnets if len(raw) < 3: # if we get enough lines for our sonnet: if countLine == 14: rhymesLine = [] # make a list of the rhymes we found in our sonnet for pair in rhymeInd: rhymesLine.append([lastWordsLst[pair[0]], lastWordsLst[pair[1]]]) # go through all of the rhymes that we got from the current sonnet # and add them to the total number of rhymes list_rhymes, rhymesLine = joinRhymeFamily(list_rhymes, rhymesLine) # go through the list of rhymes and consolidate the rhyme families if # several different families are actually just the same list_rhymes = consolidateRhymeFamily(list_rhymes) countLine = 0 lastWordsLst = [] continue raw_punc = [] # Separate any punctuation at the start or end of the word from the word itself for w in raw: if len(w) < 1: continue to_append = [] while len(w) > 0 and w[0] in punctuation: raw_punc.append(w[0]) w = w[1:] while len(w) > 0 and w[-1] in punctuation: to_append.insert(0, w[-1]) w = w[:-1] raw_punc += [w] + to_append raw = raw_punc # If we encounter a new word for the first time, add it to word_list seqs.append([]) # Add the buffer # If our sequence length mod 14 = 0, 4, 8, 12 # Then don't append the previous sequence words if not countLine % 14 in [0, 4, 8, 12]: # Append the last line to the sequence #for a in prev: #seqs[-1].append(a) # Append last line's last word to sequence seqs[-1].append(lastWordsLst[-1]) for word in raw: # Automatically lower-case the first word in each line if raw.index(word) == 0: word = word.lower() if word not in word_list: word_list.append(word) seqs[-1].append(word_list.index(word)) # Append the last word of the sequence to lastWordLst, make sure we don't get a '#' lastWordsLst.append(ignore_punctuation(seqs[-1])[-1]) #print('new lastWordsLst:', lastWordsLst) countLine += 1 prev = seqs[-1] #f.close() # Create a list of words and their possible syllable counts f2 = open('data/Syllable_dictionary.txt', 'r') syllable_counts = {} for line in f2: raw = line.strip().split() #word_index = word_list.index(raw[0]) syllable_counts[raw[0]] = raw[1:] for p in punctuation: syllable_counts[p] = 0 print('len(word_list)', len(word_list), word_list[0]) #print('word_list:') #for i in range(len(word_list)): # print(i, word_list[i]) #print('len(seqs)', len(seqs), seqs[0]) print('list of rhymes:', len(list_rhymes)) #set_rhymes = [] #for line in list_rhymes: # print([word_list[x] for x in line]) # #set_rhymes.append([word_list[x] for x in line]) # print(line) return word_list, seqs, syllable_counts, list_rhymes # go through all of the rhymes that we've found so far total and add our rhymes to them # we're adding rhymes to list_rhymes def joinRhymeFamily(list_rhymes, rhymesLine): for rhymeLocal in rhymesLine: flagRhyme = True # if we didn't find a rhyme family for rhymeTotal in list_rhymes: if rhymeLocal[0] in rhymeTotal and rhymeLocal[1] not in rhymeTotal: rhymeTotal.append(rhymeLocal[1]) flagRhyme = False elif rhymeLocal[1] in rhymeTotal and rhymeLocal[0] not in rhymeTotal: rhymeTotal.append(rhymeLocal[0]) flagRhyme = False elif rhymeLocal[1] in rhymeTotal and rhymeLocal[0] in rhymeTotal: flagRhyme = False #print('rhymesLine', len(rhymesLine)) #print('list_rhymes', len(list_rhymes)) # if we don't find a rhyme family, start a new one if flagRhyme: list_rhymes.append(rhymeLocal) #print('joined rhyme fam') return list_rhymes, rhymesLine # the point of this is to make sure that we consolidate all of # the rhyme families in discovery of new similar rhymes # check to make sure that we don't have two different lists # with the same rhyme family def consolidateRhymeFamily(list_rhymes): tempList_rhymes = [] # keeps track of what indices we've been through in # list_rhymes and where they are in tempList_rhymes indicDict = {} for i in range(len(list_rhymes) -1): for j in range(1, len(list_rhymes)): flagGetOuti = False for k in range(len(list_rhymes[i])): # if i has already been added to tempList get out if flagGetOuti: break if list_rhymes[i][k] in list_rhymes[j]: flagGetOuti = True # new element in tempList_rhymes if i not in indicDict and j not in indicDict: #diff_sets = set(list_rhymes[i]) - set(list_rhymes[j]) uniqueEl = list(set(list_rhymes[i] + list_rhymes[j])) tempList_rhymes.append(uniqueEl) indicDict[i] = len(tempList_rhymes) -1 indicDict[j] = len(tempList_rhymes) -1 if len(uniqueEl) != len(set(uniqueEl)): print('1 repeats occurred here') print('uniqueEl', uniqueEl) # updating element in tempList_rhymes, with j elif i in indicDict and j not in indicDict: #diff_sets = set(tempList_rhymes[indicDict[i]]) - set(list_rhymes[j]) uniqueEl = list(set(tempList_rhymes[indicDict[i]] + list_rhymes[j])) tempList_rhymes[indicDict[i]] = uniqueEl indicDict[j] = indicDict[i] if len(uniqueEl) != len(set(uniqueEl)): print('2 repeats occurred here') print('uniqueEl', uniqueEl) # updating element in tempList_rhymes, with i elif j in indicDict and i not in indicDict: diff_sets = set(tempList_rhymes[indicDict[j]]) - set(list_rhymes[i]) uniqueEl = tempList_rhymes[indicDict[j]] + list(diff_sets) tempList_rhymes[indicDict[j]] = uniqueEl indicDict[i] = indicDict[j] if len(uniqueEl) != len(set(uniqueEl)): print('3 repeats occurred here') #print('tempList_rhymes:') #for lst in tempList_rhymes: # print(lst) # if len(lst) is not len(set(lst)): # print('repeats occurred here') # set list_rhymes such that all the rhymes are together and consolidated list_rhymes = copy.deepcopy(tempList_rhymes) #print('consolidated rhymes') return list_rhymes def int_to_onehot(n, n_max): # Return n encoded as a one-hot vector of length n_max. return [0 if n != i else 1 for i in range(n_max)] def character_onehot(n=40, s=5, ds=0): ''' Arguments: n - the number of characters per example s - the spacing between successive examples ds - offset of each example (change from default to obtain unique validation sets) Note: 0 <= ds < s Return: X - A list of examples of length n Y - A list of characters that immediately follow Note: both X and Y are one-hot encoded ascii-values ''' data = '' # Load lines of actual Shakespeare into a single string with open(os.path.join('data', 'shakespeare.txt')) as f: for line in f: if len(line.strip().split()) < 2: continue else: data += line X = [] Y = [] # to convert back, use ''.join(chr(i) for i in L), stackoverflow.com/questions/180606 ascii_values = [ord(c) for c in data] # Generate samples of size n where successive samples are shifted by s for i in range(len(data) // s): if s * i + n + ds < len(data): X.append([int_to_onehot(a, 128) for a in ascii_values[s*i+ds:s*i+n+ds]]) Y.append(int_to_onehot(ascii_values[s*i+n+ds], 128)) return np.array(X), np.array(Y) def build_wordlist(): ''' Arguments: (none) Return: word_list - a list of the unique words, including '\n' seq - A list of integers representing all input sonnets concatenated. Each index corresponds to an entry in word_list. ''' word_list = [] # we count newline as a word pairs = [] seq = [] punctuation = ['.', '!', ',', '?', ':', ';', '(', ')'] # Load data into a single sequence f = open('data/shakespeare.txt', 'r') for line in f: line_nopunc = ''.join([c for c in line if c not in punctuation]).lower() raw = line_nopunc.strip().split() # Skip lines that aren't actually part of the Sonnets if len(raw) < 2: continue # If we encounter a new word for the first time, add it to word_list for word in raw: if word not in word_list: word_list.append(word) seq.append(word_list.index(word)) f.close() return word_list, seq def wordpair_onehot(word_list, seq, s=2): ''' Returns pairs of words (onehot-encoded) as examples for word2vec Arguments: s - The second word in the pair is selected from the window i-s to i+s, not including i itself, for a total of 2s examples per word Return: word_list - A list of words where the index corresponding to a word is its word index pairs - A list of pairs of onehot encoded words ''' trainX = [] trainY = [] L = len(word_list) # Loop over each word in the word_list for the first word for i, w in enumerate(seq): # Find the list of nearby words l = max(0, i - s) r = min(len(seq), i + 1 + s) near = seq[l:i] + seq[i+1:r] # Add each pair to X, Y for w2 in near: trainX.append(int_to_onehot(w, L)) trainY.append(int_to_onehot(w2, L)) return np.array(trainX), np.array(trainY) def word_examples(word_list, seq, n=20, s=3, ds=0, onehot=True): ''' Arguments: n - the number of words per example s - the spacing between successive examples ds - offset of each example (change from default to obtain unique validation sets) Note: 0 <= ds < s Return: X - A list of examples of length n Y - A list of words that immediately follow Note: both X and Y are one-hot encoded words ''' X = [] Y = [] L = len(word_list) # Generate samples of size n where successive samples are shifted by s for i in range(len(seq) // s): if s * i + n + ds < len(seq): if onehot: X.append([int_to_onehot(a, L) for a in seq[s*i+ds:s*i+n+ds]]) Y.append(int_to_onehot(seq[s*i+n+ds], L)) else: X.append(seq[s*i+ds:s*i+n+ds]) Y.append(int_to_onehot(seq[s*i+n+ds], L)) # Y.append(seq[s*i+n+ds]) if onehot: return np.array(X), np.array(Y) else: return X, np.array(Y)
# -*- coding: utf-8 -*- """ Created on Mon May 6 2019 @author: Seahymn, Daniel Lin """ import pickle import csv import os import pandas as pd # Separate '(', ')', '{', '}', '*', '/', '+', '-', '=', ';', '[', ']' characters. def SplitCharacters(str_to_split): #Character_sets = ['(', ')', '{', '}', '*', '/', '+', '-', '=', ';', ','] str_list_str = '' if '(' in str_to_split: str_to_split = str_to_split.replace('(', ' ( ') # Add the space before and after the '(', so that it can be split by space. str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if ')' in str_to_split: str_to_split = str_to_split.replace(')', ' ) ') # Add the space before and after the ')', so that it can be split by space. str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '{' in str_to_split: str_to_split = str_to_split.replace('{', ' { ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '}' in str_to_split: str_to_split = str_to_split.replace('}', ' } ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '*' in str_to_split: str_to_split = str_to_split.replace('*', ' * ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '/' in str_to_split: str_to_split = str_to_split.replace('/', ' / ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '+' in str_to_split: str_to_split = str_to_split.replace('+', ' + ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '-' in str_to_split: str_to_split = str_to_split.replace('-', ' - ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '=' in str_to_split: str_to_split = str_to_split.replace('=', ' = ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if ';' in str_to_split: str_to_split = str_to_split.replace(';', ' ; ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '[' in str_to_split: str_to_split = str_to_split.replace('[', ' [ ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if ']' in str_to_split: str_to_split = str_to_split.replace(']', ' ] ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '>' in str_to_split: str_to_split = str_to_split.replace('>', ' > ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '<' in str_to_split: str_to_split = str_to_split.replace('<', ' < ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '"' in str_to_split: str_to_split = str_to_split.replace('"', ' " ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '->' in str_to_split: str_to_split = str_to_split.replace('->', ' -> ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '>>' in str_to_split: str_to_split = str_to_split.replace('>>', ' >> ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if '<<' in str_to_split: str_to_split = str_to_split.replace('<<', ' << ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if ',' in str_to_split: str_to_split = str_to_split.replace(',', ' , ') str_list = str_to_split.split(' ') str_list_str = ' '.join(str_list) if str_list_str is not '': return str_list_str else: return str_to_split def SavedPickle(path, file_to_save): with open(path, 'wb') as handle: pickle.dump(file_to_save, handle) def Save3DList(save_path, list_to_save): with open(save_path, 'w', encoding='latin1') as f: wr = csv.writer(f, quoting=csv.QUOTE_ALL) wr.writerows(list_to_save) def Save2DList(save_path, list_to_save): with open(save_path, 'w', encoding='latin1') as f: wr = csv.writer(f, quoting=csv.QUOTE_ALL) wr.writerow(list_to_save) def ListToCSV(list_to_csv, path): df = pd.DataFrame(list_to_csv) df.to_csv(path, index=False) def LoadPickleData(path): with open(path, 'rb') as f: loaded_data = pickle.load(f) return loaded_data # Remove ';' from the list. def removeSemicolon(input_list): new_list = [] for line in input_list: new_line = [] for item in line: if item != ';' and item != ',': new_line.append(item) new_list.append(new_line) return new_list # Further split the elements such as "const int *" into "const", "int" and "*" def ProcessList(list_to_process): token_list = [] for sub_list_to_process in list_to_process: sub_token_list = [] if len(sub_list_to_process) != 0: for each_word in sub_list_to_process: # Remove the empty row each_word = str(each_word) sub_word = each_word.split() for element in sub_word: sub_token_list.append(element) token_list.append(sub_token_list) return token_list def getCFilesFromText(path): files_list = [] file_id_list = [] if os.path.isdir(path): for fpath,dirs,fs in os.walk(path): for f in fs: if (os.path.splitext(f)[1] == '.c'): file_id_list.append(f) if (os.path.splitext(f)[1] == '.c'): with open(fpath + os.sep + f, encoding='latin1') as file: # the encoding can also be utf-8 lines = file.readlines() file_list = [] for line in lines: if line is not ' ' and line is not '\n': # Remove sapce and line-change characters sub_line = line.split() new_sub_line = [] for element in sub_line: new_element = SplitCharacters(element) new_sub_line.append(new_element) new_line = ' '.join(new_sub_line) file_list.append(new_line) new_file_list = ' '.join(file_list) split_by_space = new_file_list.split() files_list.append(split_by_space) return files_list, file_id_list # Data labels are generated based on the sample IDs. All the vulnerable function samples are named with CVE IDs. def GenerateLabels(input_arr): temp_arr = [] for func_id in input_arr: temp_sub_arr = [] if "cve" in func_id or "CVE" in func_id: temp_sub_arr.append(1) else: temp_sub_arr.append(0) temp_arr.append(temp_sub_arr) return temp_arr
#send email through python through tls #reference: https://realpython.com/python-send-email/ import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart sender_email = "[email protected]" receiver_email = "[email protected]" password = input("Type your password and press enter:") # Create message container - the correct MIME type is multipart/alternative. message = MIMEMultipart("alternative") message["Subject"] = "multipart test" message["From"] = sender_email message["To"] = receiver_email # Create the plain-text and HTML version of your message text = """ Hi, How are you? This is a text email """ html = """ <html> <body> <p>Hi,<br> How are you?<br> This is a html email<br> </p> </body> </html> """ # Turn these into plain/html MIMEText objects part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") # Add HTML/plain-text parts to MIMEMultipart message message.attach(part1) message.attach(part2) # Create secure connection with server and send email with smtplib.SMTP("smtp.domain.com", 587) as smtp: smtp.login(sender_email, password) smtp.sendmail( sender_email, receiver_email, message.as_string() )
# Programá una función ord_burbujeo(lista) que implemente este método # de ordenamiento. ¿Cuántas comparaciones realiza esta función en una lista de largo n? lista_1 = [1, 2, -3, 8, 1, 5] lista_2 = [1, 2, 3, 4, 5] lista_3 = [0, 9, 3, 8, 5, 3, 2, 4] lista_4 = [10, 8, 6, 2, -2, -5] lista_5 = [2, 5, 1, 0] # Agrego otra lista de más elementos para hacer más evidente la complejidad lista_6 = [3,234,3,45,21,-123,34-1233,0,90,34,-4,-9,123123,123,123,4,3,5,6,4,3,5,6] def ord_burbujeo(lista): lista_copy = lista.copy() steps = 0 for _ in lista_copy: for j,_ in enumerate(lista_copy[:-1]): steps += 1 if lista_copy[j] > lista_copy[j+1]: aux = lista_copy[j] lista_copy[j] = lista_copy[j+1] lista_copy[j+1] = aux return lista_copy,steps listas = [lista_1, lista_2, lista_3, lista_4, lista_5, lista_6] resultados = [ ord_burbujeo(lista_n) for lista_n in listas ] print(resultados) # analizar complejidad según largo de la lista import pandas as pd import matplotlib.pyplot as plt x_axis = [len(lista_n[0]) for lista_n in resultados] y_axis = [lista_n[1] for lista_n in resultados] data = pd.DataFrame({'lenghts':x_axis,'steps':y_axis}) data.plot(x='lenghts',y='steps',kind='scatter') plt.show() #En el gráfico se ve que se comporta de forma cuadrática
''' Las columnas en camion.csv corresponden a un nombre de fruta, una cantidad de cajones cargados en el camión, y un precio de compra por cada cajón de ese grupo. Escribí un programa llamado costo_camion.py que abra el archivo, lea las líneas, y calcule el precio pagado por los cajones cargados en el camión. ''' import csv def costo_camion(dataUrl): with open(dataUrl) as truckDataRaw: # uso csv module truckData = csv.reader(truckDataRaw) headings = next(truckData) cost = 0 for i,boxData in enumerate(truckData, start=2): formatData = dict(zip(headings,boxData)) #para cada caja intento sacarle los datos try: cost += int(formatData['cajones']) * float(formatData['precio']) except ValueError: print(f'Línea {i} con datos ilegibles en el archivo! Ignorando...{boxData}') continue return cost costo = costo_camion('../Data/missing.csv') print(f'Costo Total en missing.csv: {costo}') costo = costo_camion('../Data/fecha_camion.csv') print(f'Costo Total en fecha_camion.csv: {costo}')
#http://projecteuler.net/problem=7 #By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. #What is the 10 001st prime number? #bruteforce power primes = [] num = 2 def is_prime(n): for prime in primes: if n % prime == 0: return False return True while len(primes) != 10001: if is_prime(num): primes.append(num) num += 1 print(primes[10000])
# A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # similar to an object literal # Create dict person = { 'first_name': 'John', 'last_name': 'Doe', 'age': 30 } # trying to access a key they doesn't exist ex: 'gender' returns KeyError # Use constructor # person2 = dict(first_name='Sara', last_name='Williams') # Get value print(person['first_name']) print(person.get('last_name')) # you can also you in/not in to check keys print('first_name' in person) #true print('gender' in person) #false print('gender' not in person) #true # get method, similar to index but returns None if not found print(person.get('first_name')) # John print(person.get('email')) # None print(person.get(12345, "not in dictionary")) # not in dictionary print(person.get('last_name', "not in dictionary")) # Doe # Add key/value person['phone'] = '555-555-5555' # Get dict keys print(person.keys()) # Get dict items print(person.items()) # Copy dict person2 = person.copy() person2['city'] = 'Boston' # Remove item del(person['age']) person.pop('phone') # Clear person.clear() # Get length print(len(person2)) # List of dict people = [ {'name': 'Martha', 'age': 30}, {'name': 'Kevin', 'age': 25} ] print(people[1]['name']) # When to use a dictionary: # - When you need a logical association between a key:value pair. # - When you need fast lookup for your data, based on a custom key. # - When your data is being constantly modified. Remember, dictionaries are mutable. # When to use the other types: # - Use lists if you have a collection of data that does not need random access. Try to choose lists when you need a simple, iterable collection that is modified frequently. # - Use a set if you need uniqueness for the elements. # - Use tuples when your data cannot change.
"""Draws echograms of NumPy ndarrays as used in the echonix library. """ import matplotlib.pyplot as plt import matplotlib.colors as colors import numpy as np import numpy.ma as ma import math def ek500(): """ek500 - return a 13x3 array of RGB values representing the Simrad EK500 color table """ rgb = [(1, 1, 1), (159/255, 159/255, 159/255), (95/255, 95/255, 95/255), (0, 0, 1), (0, 0, 127/255), (0, 191/255, 0), (0, 127/255, 0), (1, 1, 0), (1, 127/255, 0), (1, 0, 191/255), (1, 0, 0), (166/255, 83/255, 60/255), (120/255, 60/255, 40/255)] return rgb def egshow(a, min=None, max=None, range=None, cmap=None): """Draws an echogram using the NumPy ndarray a. """ x, y = a.shape a = np.transpose(a) if min is None: min = np.nanmin(a) if max is None: max = np.nanmax(a) if not np.ma.is_masked(a) and np.isnan(a).any(): a = ma.array(a, mask=np.isnan(a)) if cmap is None: cmap = colors.ListedColormap(ek500(), "A") plt.pcolormesh(a, cmap=cmap, vmin = min, vmax = max) plt.gca().invert_yaxis() if range is None: top = 0 bottom = y elif isinstance(range, tuple): top, bottom = range else: top = 0 bottom = range stepr = 10**(int(math.log10(bottom-top))) stepy = y * stepr / (bottom-top) yticks = np.arange(0, y, stepy) yticklabels = np.arange(top, bottom, stepr).astype(int) if len(yticks) < 3: yticks = np.arange(0, y, stepy/5) yticklabels = np.arange(top, bottom, stepr/5).astype(int) plt.gca().set_yticks(yticks) plt.gca().set_yticklabels(yticklabels) def imshow(a, range=None, aspect='auto'): """Draws an echogram like view of the pillow image a. Useful for displaying composite images. """ x, y = a.size if range is None: top = 0 bottom = y elif isinstance(range, tuple): top, bottom = range else: top = 0 bottom = range stepr = 10**(int(math.log10(bottom-top))) stepy = y * stepr / (bottom-top) yticks = np.arange(0, y, stepy) yticklabels = np.arange(top, bottom, stepr).astype(int) if len(yticks) < 3: yticks = np.arange(0, y, stepy/5) yticklabels = np.arange(top, bottom, stepr/5).astype(int) plt.gca().set_yticks(yticks) plt.gca().set_yticklabels(yticklabels) plt.imshow(a, aspect=aspect)
''' This is the python solution for the following hackerrank question: https://www.hackerrank.com/challenges/merge-the-tools/problem ''' def merge_the_tools(string, k): substrs = list() substr = list() final_s = list() for i in range(0,len(string),k): substrs.append(string[i:i+k]) for x in substrs: for y in x: if y not in substr: substr.append(y) final_s.append(''.join(substr)) substr.clear() print(*final_s,sep='\n') if __name__ == '__main__': string,k = input() , int(input()) merge_the_tools(string,k)
#/usr/bin/python class Employee: raise_amount = 1.04 No_of_emps = 0 def __init__(self, first, last, salery): self.fname = first self.lname = last self.pay = salery self.email = first + last + '@netmagic.com' Employee.No_of_emps += 1 def fullname(self): return self.fname+' '+self.lname def apply_raise(self): self.pay = int(self.pay * self.raise_amount) print (Employee.No_of_emps) emp_1 = Employee('vaibhav', 'gaurihar', 60000) emp_2 = Employee('rakesh', 'khatpal', 100000) Employee.raise_amount = 1.05 emp_1.raise_amount = 1.06 print (Employee.No_of_emps) print (Employee.raise_amount) print (emp_1.raise_amount) print (emp_2.raise_amount)
#!C:\Python27\python.exe # -*-coding: utf-8 -*- import math var1 = raw_input("eneter the value?. ") def factorial(n): if int(n) < 0: print "Factorial is only defined for positive integers." return -1 elif int(n) == 0: return 1 elif int(n) > 0: return int(n) * factorial(int(n)-1) else: print "Factorial is only defined for integers." return -1 result = factorial(var1) print result
##Fibonacci series program ##a series of numbers in which each number ( Fibonacci number ) is ##the sum of the two preceding numbers. The simplest is the series ##1, 1, 2, 3, 5, 8, etc. ## Program to display the Fibonacci sequence up to n-th term ##where n is provided by the user. x = int(input("enter the n-th term. ")) ### first two terms ##n1 = 0 ##n2 = 1 ##count = 0 ## ### check if the number of terms is valid ##if x <= 0: ## print("Please enter positive integer") ##elif x == 1: ## print("Fibonacci sequence of.", x, ": 0") ##else: ## print("Fibonacci sequence upto", x) ## while count < x: ## print(n1,end=',') ## nth = n1 + n2 ## #Update Value ## n1 = n2 ## n2 = nth ## count += 1 def fib(n): a,b = 0,1 for i in range(n): print(a,end=',') a,b = b,a+b return '' print (fib(x))
WHITE = "WHITE" BLACK = "BLACK" GREY = "GREY" TIME = 0 class Vertex: def __init__(self, key): self.key = key self.adjlist = {} def display(self): print "Key = %s\tEdges = %s" % (self.key, str(self.adjlist.keys())) def __repr__(self): return "%s: %s" % (str(self.key), str(self.adjlist.keys())) class Graph: def __init__(self): self.vertices = {} def add_vertex(self, key): self.vertices[key] = Vertex(key) def add_directed_edge(self, fromv, tov, weight): self.vertices[fromv].adjlist[tov] = weight def add_undirected_edge(self, fromv, tov, weight): self.add_directed_edge(fromv, tov, weight) self.add_directed_edge(tov, fromv, weight) def create(self): print "Graph creation helper" directed = False directedq = raw_input("Is this a directed graph (y or n)?") if directedq.lower() == 'y': directed = True while 1: v = raw_input("Enter Vertex key, hit 'q' when finished:\t") if v=='q': break self.add_vertex(v) while 1: s = raw_input("Starting vertex ('q' to exit):\t") if (s == 'q'): break e = raw_input("Ending vertex:\t") if directed: self.add_directed_edge(s,e,1) else: self.add_undirected_edge(s,e,1) def display(self): for vert in self.vertices.values(): vert.display() def dfs_visit(self, vert, verbose, list): global TIME TIME += 1 vert.d = TIME vert.color = GREY for v in vert.adjlist.keys(): u = self.vertices[v] if u.color == WHITE: u.parent = vert list = self.dfs_visit(u, verbose, list) vert.color = BLACK list.append(vert) if verbose: print "Visited " + str(vert.key) TIME += 1 vert.f = TIME return list def dfs(self, verbose): global TIME list = [] for vert in self.vertices.values(): vert.color = WHITE vert.parent = None vert.d = -1 vert.f = -1 TIME = 0 for vert in self.vertices.values(): if vert.color == WHITE: list = self.dfs_visit(vert, verbose, list) return list def bfs(self, vertex, target): visited = [] self.vertices[vertex].d = 0 queue = [self.vertices[vertex]] d = 0 while len(queue) > 0: u = queue[0] visited.append(u) if u.key == target: return (u, d) queue = queue[1:] for v in u.adjlist.keys(): vert = self.vertices[v] if ((vert not in visited) and (vert not in queue)): print "Adding %s to queue" % vert queue.append(vert) d += 1 if __name__ == "__main__": g = Graph() g.create() g.display() #print g.bfs('1','3') print g.dfs(True)
import random def get_data(): """返回0到9之间的3个随机数""" return random.sample(range(10), 3) def consume(): """显示每次传入的整数列表的动态平均值""" running_sum = 0 data_items_seen = 0 while True: data = yield #生成器接收点 关键点 data_items_seen += len(data) # 每次调用值将会保留,下次执行的时候将会调用该值 running_sum += sum(data) # print('The running average is {}'.format(running_sum / float(data_items_seen))) def produce(consumer): """产生序列集合,传递给消费函数(consumer)""" while True: data = get_data() print('Produced {}'.format(data)) consumer.send(data) #关键点 #通过 send 方法来将一个值“发送”给生成器。 yield #设置生成器 if __name__ == '__main__': consumer = consume() consumer.send(None) #启动生成器 producer = produce(consumer) for _ in range(3): print('Producing...') next(producer) ########### 执行结果 ################ # 传递进去的值不会随着函数接收而消失,而是暂时进行了保存(以供下次使用); # Producing... # Produced [0, 9, 8] # The running average is 5.666666666666667 # Producing... # Produced [2, 3, 1] # The running average is 3.8333333333333335 # Producing... # Produced [3, 5, 2] # The running average is 3.666666666666666
#!/usr/bin/python3 # 功能:登陆login/register user_data = {} '提示' def tip(): print("###### 新建用户:N/n ######") print("###### 登陆用户:E/e ######") print("###### 登陆用户:Q/q ######") '注册模块' def reg(): name = input("请输入注册名用户名") while True: if name in user_data: name = input("用户名已被占用,请重新输入:") else: break password = input("请输入密码:") user_data.setdefault(name, password) print("Ok.注册成功") '登陆模块' def login(): name = input("请输入登陆的账户:") while True: if name not in user_data: name = input("输入的用户名不存在,请重新输入用户名:") else: break password = input("请输入密码:") if user_data[name] == password: print("Ok.登陆成功") else: print("Error.密码错误") '主模块' def user(): tip() while 1: temp = input("|---请输入指令代码:") if temp.lower() == 'n': reg() if temp.lower() == 'e': login() if temp.lower() == 'q': break print("退出成功,欢迎下次使用!") user() #调用主模块
#!/usr/bin/python3 #功能:内嵌函数与闭包使用 #""" 内嵌函数 """ def fun1(): print("Fun1 主函数被调用") def fun2(): print("Fun2 内嵌函数正在被调用\n") fun2() #内部函数(内嵌函数),只能由fun1()调用 fun1() #"""闭包""" def funX(x): def funY(y): return x * y return funY i = funX(8) print("i的类型 :",type(i)) print("8 * 5 =",i(5)) # 40 由于前面已经赋值给x了,后面得就给了y=5. """ 类似于 >>> def funX(x): def funY(y): return x * y return funY(2) >>> funX(3) 6 """ #"""闭包进阶(采用类似于数数组的方式 -- 列表(传入的是地址))""" def demo1(arg): x = [arg] def demo2(): #采用 nonlocal 关键字也行 x[0] **= x[0] #采用这样的方式进行取值列表 (**幂运算) | 不引用局部变量(Local variable),采用数组的方式进行暗渡成仓. return x[0] return demo2() print("2 ** 2 =",demo1(2)," - 5 ** 5 =",demo1(5)) #"""一个闭包的典型案例""" def funA(): x = 5 def funB(): nonlocal x #//把x强制表示不是局部变量local variable x += 13 return x return funB a = funA() #当 a 第一次被赋值后,只要没被重新赋值,funA()就没被释放,也就是说局部变量x就没有被重新初始化。 print("第一次调用:",a(),"第二次调用:",a(),"第三次调用:",a())
#!/usr/bin/python3 #功能:递归汉诺塔 def haoni(n,x,y,z): if n == 1: print(x,'-->',z) else: haoni(n-1,x,z,y) #前n-1从x移动到y上 print(x,'-->',z) #将最底下盘子从x移动到z上 haoni(n-1,y,x,z) #将y上的n-1盘中移动到z上 haoni(3,'a','b','c') print(list('123456799')) print(tuple([1,2,3,5])) #冻结集合(使其不能正常添加与删除元素) num = frozenset([1,2,3,4]) print(num) print(type(num))
#!/usr/bin/python3 #功能:课后作业 # try: # for i in range(3): # for j in range(3): # if i == 2: # raise KeyboardInterrupt('') # print(i,j) # except KeyboardInterrupt: # print("异常中断结束") try: f = open('My_File.txt') # 当前文件夹中并不存在"My_File.txt"这个文件T_T (而且是一个局部变量) print(f.read()) except OSError as reason: print('出错啦:' + str(reason)) finally: if 'f' in locals(): # 如果文件对象变量存在当前局部变量符号表的话,说明打开成功 f.close() import random secret = random.randint(1,10) print('------------------我爱鱼C工作室------------------') temp = input("不妨猜一下小甲鱼现在心里想的是哪个数字:") try: guess = int(temp) except ValueError: print('输入错误!') guess = secret while guess != secret: temp = input("哎呀,猜错了,请重新输入吧:") guess = int(temp) if guess == secret: print("我草,你是小甲鱼心里的蛔虫吗?!") print("哼,猜中了也没有奖励!") else: if guess > secret: print("哥,大了大了~~~") else: print("嘿,小了,小了~~~") print("游戏结束,不玩啦^_^")
class Counter: def __init__(self): self.counter = 0 # 这里会触发 __setattr__ 调用 def __setattr__(self, name, value): self.counter += 1 # 既然需要 __setattr__ 调用后才能真正设置 self.counter 的值,所以这时候 self.counter 还没有定义,所以没法 += 1,错误的根源。””” super().__setattr__(name, value) def __delattr__(self, name): self.counter -= 1 super().__delattr__(name) tet = Counter()
#!/usr/bin/python3 #功能:课后作业03 import random name = input("请输入您的姓名:") num = input('请输入一个1~100的数中:') num = int(num) if num > random.randint(0,100): print("恭喜您:" + name,"您输入的数字"+ num +"大于随机数") else: print("不能恭喜您了",name) #所见即所得 string = """ WeiyiGeek, Python, 脚本语言. """ print(string) #需要进行转义才行 string = ( "我爱鱼C,\n" "正如我爱小甲鱼,\n" "他那呱唧呱唧的声音,\n" "总缠绕于我的脑海,\n" "久久不肯散去……\n") print(string)
#!/usr/bin/python3 #功能: import random as r class Fish: def __init__(self): self.x = r.randint(0,10) self.y = r.randint(0,10) def move(self): self.x -= 1 print("我得位置是:",self.x,self.y) class Shark(Fish): def __init__(self): super().__init__() #方法1:只需要传入父类即可 #Fish.__init__(self) #方法2: 调用类狗构造方法 self.hungry = True def eat(self): if self.hungry: print("饿了,要吃饭@!") self.hungry = False else: print("太撑了,吃不下了") demo = Fish() demo.move() demo1 = Shark() demo1.eat() demo1.eat() #/***多重继承(继承)**/# class Base1: def printf1(self): print("Base1: 父类") class Base2: def printf2(self): print("Base2: 父类") class Pool(Base1,Base2): def child(self): print("我是子类") tt = Pool() tt.child() tt.printf1() tt.printf2() #****类得组合(横向)***# class Turtle: def __init__(self,x): self.num = x class Fishe: def __init__(self, x): self.num = x class Aini: def __init__(self, x, y): self.turtle = Turtle(x) self.fishe = Fishe(y) def print_num(self): print("水池里总共乌龟 %d 只,小鱼 %d 条" %(self.turtle.num,self.fishe.num)) demo3 = Aini(5,6) demo3.print_num() #类绑定 class CC: def setXY(self,x,y): self.x = x self.y = y def printXY(self): print(self.x,self.y) dd = CC() #实例化对象 dd.setXY(5,7) del CC #这里删除了定义CC类,但是实例化得dd对象并不会被销毁,而是在程序结束后进行释放 dd.printXY() #任然可以打印
#!/usr/bin/python3 #coding:utf-8 #功能:分支与循环 #-----------if 语句----------------- guess = 8 temp = int(input("请输入一个1-10数值:")) if guess == temp: print("恭喜您,输入的数值刚好") elif guess > temp: print("太遗憾了,输入的数值小于它") else: print("太遗憾了,输入的数值大于它") x,y = 1,3 print("#三元运算符 :",end="") print( x if x > 3 else y ) #------------while 语句--------------- # Fibonacci series: 斐波纳契数列 (两个元素的总和确定了下一个数) a,b = 0,1 while b < 10: print(b,end=",") a,b = b, a+b print("\n\n") #------------for 语句--------------- for i in "python": print(i,end="|") #依次打印字母并以 | 分割 print() sites = ["baidu","Google","Runoob","taobao"] for i in sites: print(i,end=",") #打印出列表的值 print() for i in range(len(sites)): #或列表的长度 4 生成(0 - 3); print(i,sites[i],len(sites[i])) #索引,列表中以索引下标的元素,元素的长度 print() #查询是否为质数 2 - 10 那些是质数 for x in range(2,10): for y in range(2,x): if x % y == 0: print(x,'等于',y , '*', x // y) break else: #循环中找到元素,它在穷尽列表(以for循环)或条件变为 false (以while循环)导致循环终止时被执行,但循环被break终止时不执行。 print(x,'是质数')
#!/usr/bin/python3 #min 内置函数的实现 与 sum bug 解决 def min(x): initvalue = x[0] for each in x: if each < initvalue: #实际采用的ASCII进行比对的 initvalue = each else: print("计算成功") return initvalue print(min('178546810')) def sum(x): result = 0 for each in x: if isinstance(each,int) or isinstance(each,float): result += each return result; print(sum([1,3,6.6,'y',"abcd"]))
# -*- coding: utf8 -*- origin = (0,0) legalx = [-100,100] legaly = [-100,100] def create(posx=0,posy=0): def moving(direction,step): # direction参数设置方向,1为向右(向上),-1为向左(向下),0为不移动 # step参数设置移动的距离 nonlocal posx,posy newx = posx + direction[0] * step newy = posy + direction[1] * step # 检查移动后是否能够超出X轴边界 if newx<legalx[0]: posx = legalx - (newx - legalx) # -100 - (-101 + 100) => -100 + 1 ==> -99 elif newx > legalx[1]: posx = legalx[1] - (newx - legalx[1]) # 100 - (101 - 100) => 99 else: posx = newx #注意这里,会返回到下一次的调用之中 # 检查移动后是否超出y轴边界 if newy < legaly[0]: posy = legaly - (newy - legaly) elif newy > legaly[1]: posy = legaly[1] - (newy - legaly[1]) else: posy = newy return posx,posy return moving move = create() print('向右移动10步后,位置是:', move([1, 0], 10)) print('向上移动130步后,位置是:', move([0, 1], 130)) print('向左移动10步后,位置是:', move([-1, 0], 10))
#!/usr/bin/python class MyDes: def __init__(self, value = None): self.val = value def __get__(self, instance, owner): return self.val ** 2 class Test(MyDes): x = MyDes(3) test = Test() print(test.x)
#!/usr/bin/python3 #功能:Python对象编程学习 # #/***类封装**/# # class Person: # name = 'Weiyigeek' # age = 20 # msg = 'I Love Python' # def detail(self): # print('姓名 :',self.name,"年龄:",self.age, "爱好:",self.msg) # oop = Person() # oop.detail() # #/***类继承**/# # class mylist(list): # pass # list2 = mylist() # list2.append(10) #继承了list类得方法 # list2.append(2) # list2.append(3) # list2.sort() #继承了list类得方法 # print(list2) # #/***类多态**/# # class A: # def fun(self): # print("我是小A....") # class B: # def fun(self): # print("我是小B....") #self 方法得使用 class selfdemo: def __init__(self,name): self.name = name def demo1(self,name): self.name = name def demo2(self): print("我是 %s 得对象" %self.name) a = selfdemo("Weiyigeek") a.demo1("Weiyigeek") b = selfdemo("Weiyigeek") b.demo1("Python") a.demo2() b.demo2() #___init___(self) #私有函数 class Person1: __name = 'Weiyigeek' #类得私有变量 def getpri(self): return self.__name tt = Person1() print("类私有变量变量得输出",tt.getpri()) 调用未绑定得父类方法,使用super函数
#!/usr/bin/python3 #功能:课后作业04 count = input("请输入显示*号的个数:") count = int(count) while count: print(' ' * (count - 1),'*' * count) count = count - 1 else: print("打印结束")
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ r=len(matrix) if matrix: c=len(matrix[0]) else: c=0 l=r*c start=0 end=l-1 while(start<=end): mid=(start+end)/2 i=mid/c j=mid%c if target==matrix[i][j]: return True elif target>matrix[i][j]: start=mid+1 else: end=mid-1 return False
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ st=str(x) f=0 if st[0]=='-': f=1 st=st[1:] st=st[::-1] if f==1: x= int('-'+st) else: x= int(st) #print x if(x>2**31 or x <-(2**31)): return 0 else: return x
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if(root!=None): q=deque() q.append(root) count=1 ans=[] ans.append([root.val]) d=1 while(len(q)>0): d*=-1 children=0 temp=[] while(count!=0): c=q.popleft() if(c.left!=None): q.append(c.left) temp.append(c.left.val) children+=1 if(c.right!=None): q.append(c.right) temp.append(c.right.val) children+=1 count-=1 count=children if(len(temp)>0): if(d==-1): temp.reverse() ans.append(temp) else: ans.append(temp) return ans else: return []
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def eraseOverlapIntervals(self, intervals): """ :type intervals: List[Interval] :rtype: int """ intervals=sorted(intervals,key=lambda s: (s.end)) count=0 for i in range(len(intervals)): if i==0: continue if intervals[i].start<intervals[i-1].end: count+=1 intervals[i].start=intervals[i-1].start intervals[i].end=intervals[i-1].end return count
arr = [8,5,2,6,9,3,1,4,0,7,3,6,7,89,4,2,34,33333,1,3,5,67,78,6,0,0,1,3] def insertionSort(arr): for i in range(1, len(arr)): k = arr[i] j = i - 1 while j >= 0 and arr[j] > k: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = k return arr print(insertionSort(arr))
class Comment(object): """ Youtube Comment class """ def __init__(self, text, comment_id, video_id, sentiment =''): """Method for initializing a Comment object Args: text (str) video_id (int) comment_id (str) Attributes: text : comment text video_id : unique video_id associated with the comment comment_id : comment_id """ self.text = text self.comment_id = comment_id self.video_id = video_id self.sentiment = sentiment def set_sentiment(self, sentiment): """Method for setting the sentiment of a comment Args: sentiment (str) Returns: None """ self.sentiment = sentiment
"""Reuben Koshy""" password = input("Enter a Password: ") while len(password) >= 0: if len(password) >= 8: print("Valid Password") print('*' * len(password)) break else: print("Invalid password. Must be at least 8 characters in length") password = input("Enter a Password: ")
import keras from keras import Sequential, Input # NNのモデルを作る際に使用 from keras.layers import Conv2D, MaxPooling2D # NNの部品 from keras.layers import Activation, Dropout, Flatten, Dense # NNの部品 Denseは全結合層 from keras.utils import np_utils # import numpy as np import warnings warnings.simplefilter('ignore') classes = ['monkey', 'boar', 'crow'] num_classes = len(classes) image_size = 50 # 学習のモデルを定義する def main(): X_train, X_test, y_train, y_test = np.load('./animal.npy', allow_pickle=True) # 正規化 X_train = X_train.astype('float') / 256 # 正規化 X_test = X_test.astype('float') / 256 # 正規化 # ラベルのone-hot-vector化 y_train = np_utils.to_categorical(y_train, num_classes) y_test = np_utils.to_categorical(y_test, num_classes) # modelの学習 model = model_train(X_train, y_train) # modelの評価 model_eval(model, X_test, y_test) def model_train(X, y): # modelの定義 model = Sequential() model.add(Input(shape=(50, 50, 3))) model.add(Conv2D(32, 3, padding='same', activation="relu")) model.add(Conv2D(32, 3, activation="relu")) model.add(MaxPooling2D(2)) model.add(Dropout(0.25)) model.add(Conv2D(64, 3, padding='same', activation="relu")) model.add(Conv2D(64, 3, padding='same', activation="relu")) model.add(MaxPooling2D(2)) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512, activation="relu")) model.add(Dropout(0.5)) model.add(Dense(3, "softmax")) # なぜrmspropなんだろ opt = keras.optimizers.RMSprop(lr=0.0001, decay=1e-6) # loss, optimizer, metrics(評価手法)を決めてモデルを定義 model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy']) # 学習 model.fit(X, y, batch_size=32, epochs=100) # 処理が遅い場合はepoch数変えてみる # 学習したモデルの保存 model.save('./animal_cnn.h5') # modelを返さないとmodel_evalでmodelを使ってテストができない return model def model_eval(model, X, y): # modelの損失値と評価値を返す scores = model.evaluate(X, y, verbose=1) # vervose:途中結果の表示 print('Test Loss: ', scores[0]) print('Test Accuracy: ', scores[1]) # このプログラムが直接pythonから呼ばれていたらmainを実行する if __name__ == '__main__': main()
""" Using Python 2.7, or 3.3-3.5 syntax/semantics, please fill out the bodies of the included functions to include implementations of what is described in the docstrings. You can test your answers against the __basic__ included unittests by running: `python -m doctest questions.py` """ from scipy.spatial.distance import cdist, euclidean import sys import numpy as np def list_of_integers(start, end = 100): """ Returns a list of integers from 17 to 100 that are evenly divisible by 11. >>> list_of_integers() [22, 33, 44, 55, 66, 77, 88, 99] """ pass start = start or 17 range = [] while start <= 100: if start % 11 == 0: range.append(start) start += 11 else: start += 1 return range def dict_mapping(start, end = 100): """ Returns a dictionary mapping integers to their 2.75th root for all integers from 2 up to 100 (including the 2.75th root of 100). """ pass start = start or 2 dictionary = {} for i in range(end): root = i ** (1/2.75) dictionary[i] = root return dictionary def generate_cubes_until(modulus): """ Generates the cubes of integers greater than 0 until the next is 0 modulo the provided modulus. >>> list(generate_cubes_until(25)) [1, 8, 27, 64] """ pass if modulus == 0: return None total = 1 cubes = [1] i = 2 while total % modulus != 0: cube = i ** 3 total += cube cubes.append(cube) i += 1 return cubes def check_type(typ): """ Write a function decorator that takes an argument and returns a decorator that can be used to check the type of the argument to a 1-argument function. Should raise a TypeError if the wrong argument type was passed. >>> @check_type(int) ... def test(arg): ... print(arg) ... >>> test(4) 4 >>> test(4.5) Traceback (most recent call last): ... TypeError """ pass def decorator(function): def wrapper(arg): if isinstance(arg, typ): function(arg) else: raise TypeError return wrapper return decorator def left_turn(one, two, three): """ Given three points return True if they form a left turn, False if they do not If you were standing at point one, looking at point two: If point three is on your left, then these three points form a left-turn. >>> left_turn((0, 0), (2, 2), (2, 3)) True """ pass angle1 = (two[0]-one[0])*(three[1]-one[1]) angle2 = (two[1]-one[1])*(three[0]-one[0]) return (angle1-angle2) > 0 def nearest_point(candidate_points, points): """ Given a list of candidate points find the candidate point that is closest to any point in list points Feel free to add a dependency if needed >>> nearest_point([(0.1, 0.1), (2, 2), (2, 3)], [(0, 0), (5, 5), (2, 1), (2, 4)]) (0.1, 0.1) """ pass min_distance = sys.maxint closest_point = candidate_points[0] for point in points: closest = candidate_points[cdist([point], candidate_points).argmin()] distance = euclidean(point, closest) if distance < min_distance: min_distance = distance closest_point = point return tuple([x+0.0 for x in closest_point]) def round_with_threshold(point, threshold): x = point[0] y = point[1] x = round(x) if abs(round(x) - x) < threshold else x y = round(y) if abs(round(y) - y) < threshold else y return [x, y] def is_a_square(one, two, three, four, threshold=0.0): """ Given four points determine if those points form a square It's up to you how to define how square the points must be to qualify as a square >>> is_square((0, 1), (1, 1), (1, 0), (0, 0)) True >>> is_square((0, 0), (1, 1), (0, 1), (1, 0)) True >>> is_square((0.1, 0.1), (0, 1), (1, 1), (1, 0), threshold=0.2) """ pass one = round_with_threshold(one, threshold) two = round_with_threshold(two, threshold) three = round_with_threshold(three, threshold) four = round_with_threshold(four, threshold) distances = [euclidean(one, two), euclidean(one, three), euclidean(one, four), euclidean(two, one), euclidean(two, three), euclidean(two, four), euclidean(three, one), euclidean(three, two), euclidean(three, four), euclidean(four, two), euclidean(four, three), euclidean(four, one)] unique_distances = set(distances) return len(unique_distances) == 2
from gfxhat import lcd; from gfxhat import backlight; from time import sleep; import random; #CREATE A VERTICAL LINE def createVerticalLine(): lcd.clear(); lcd.show(); y = 0; x = int(input('Set the x cordinate for the vertical line: ')); while (y <= 63): lcd.set_pixel(x,y,1); y = y + 1; lcd.show(); #CREATE A HORIZONTAL LINE def createHorizontalLine(): lcd.clear(); lcd.show(); x = 0; y = int(input('Set the y cordinate for the horizontal line: ')); while (x <= 127): lcd.set_pixel(x,y,1); x = x + 1; lcd.show(); #CREATE STAIRCASE (BROKEN) def createStaircase(): lcd.clear(); lcd.show(); x = 0; y = 0; w = 23 #int(input('Enter the stair width: ')); h = 23 #int(input('Enter the height width: ')); while(x <= 127 or y <= 63): while(x <= (x + w)): lcd.set_pixel(x,y,1); x = x + 1; while(y <= (y + h)): lcd.set_pixel(x,y,1); y = y + 1; x = x + 1; y = y + 1; lcd.show(); #DISPLAY A RANDOM PIXEL FOR A TIME def randonPixel(): lcd.clear(); lcd.show(); x = random.randint(0,127); y = random.randint(0,63); timer = int(input('Enter an amount of seconds for the pixel to appear on the screen: ')); lcd.set_pixel(x,y,1); lcd.show(); sleep(5); lcd.clear(); lcd.show(); #CLEAR BACKLIGHT def clearBacklight(): lcd.clear(); lcd.show(); backlight.set_all(0,0,0); backlight.show();
# -*- coding: utf-8 -*- """ Created on Mon Dec 09 21:45:18 2013 @author: Alejandro """ class Movilidad(object): """ Se define la movilidad de los agentes. """ def __init__(self, agentId): self.id = agentId self.agentId = agentId def getAgentId(self): return self.agentId def getId(self): return self.id def getType(self): #this should be done with some sort of parent class but whatever return 'legs' def sayLegs(self): return 'I am Legs "' + self.id + '", and I am running on ' + str(self._pyroDaemon.locationStr) def howMuchToWait(self): return 15
#Make sure to un-comment the function line below when you are done. #Remember to name your function correctly. def bigger_guy(a, b): if a < b: return b else: return a #DO NOT remove lines below here,return max(1, 2, 3) #DO NOT remove lines be #this is designed to test your code. def test_bigger_guy(): assert bigger_guy (1, 2) == 2 assert bigger_guy (10, 20) == 20 assert bigger_guy (20, 10) == 20 assert bigger_guy (10, 10) == 10 assert bigger_guy (2, 1) == 2 assert bigger_guy ('a', 'b') == 'b' # 'b' is greater than 'a' print("YOUR CODE IS CORRECT!") #test your code by un-commenting the line(s) below test_bigger_guy()
class Mobil: def warna(self): print("Mobil x memiliki warna merah") class Xenia(Mobil): def warna(self): print("Mobil Xenia memiliki warna hitam") # Overriding digunakan untuk mengganti method induknya a = Xenia() a.warna() """ ========================================================== ================== Versi Python 3.8.5 ================== ================== 2021 ================== ========================================================== """
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list print list[0] print list[1:3] tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] print "3rd value in touple : ",tuple[2] tuple[2] = 1000 # Invalid syntax with tuple print "3rd value in list ",list[2] list[2] = 1000 # Valid syntax with list
########################################################################################### # Name: Garrett Miculek # # Date: 9-30-19 # # Description: Asking for a name and an age. # ########################################################################################### # prompt the user for a name and an age name = input("Please enter your name: ") print(name) age = input("How old are you, " + name + "? ") print(age) # display the final output twice =(int(age)*int(2)) print("Hi, " + name + "." " You are " + age + " years old. Twice your age is " + str(twice) + ".") print("yes")
#!/usr/bin/env python # HW04_ex08_11 # The following functions are all intended to check whether a string contains # any lowercase letters, but at least some of them are wrong. For each function, # describe what the function actually does (assuming that the parameter is a # string). # Do not merely paste the output as a counterexample into the documentation # string, explain what is wrong. ################################################################################ # Body def any_lowercase1(s): """Explain what is wrong, if anything, here. the control goes out the function after hitting the return statement the first time. This code returns boolean value True if the first letter in the string is of lowercase and False otherwise. It doesn't proceed beyond the first character of the string """ for c in s: if c.islower(): return True else: return False def any_lowercase2(s): """Explain what is wrong, if anything, here. the control goes out the function after hitting the return statement the first time. This code returns the string 'True' if the first letter in the string is of lowercase and False otherwise. It doesn't proceed beyond the first character of the string """ for c in s: if 'c'.islower(): return 'True' else: return 'False' def any_lowercase3(s): """Explain what is wrong, if anything, here. This code returns true when the last character in the string is lowercase and false otherwise """ for c in s: flag = c.islower() return flag def any_lowercase4(s): """Explain what is wrong, if anything, here. This function returns True even if there is a single lowercase letter in the string. will return false only if all the characters in the string are uppercase. """ flag = False for c in s: flag = flag or c.islower() return flag def any_lowercase5(s): """Explain what is wrong, if anything, here. """ for c in s: if not c.islower(): return False return True ################################################################################ def main(): # Remove print("Hello World!") and for each function above that is wrong, # call that function with a string for which the function returns # incorrectly print any_lowercase1("thisStringmessesupthefunction") print any_lowercase2("thisStringmessesupthefunction") print any_lowercase3("thisStringmessesupthefunction") print any_lowercase4("aaAAAAAAAAAA") print any_lowercase5("aaAa") if __name__ == '__main__': main()
import numpy as np #np.linalg.norm returns one of seven different norms of a vector a=np.arange(9)-4 b=a.reshape((3,3)) L1=np.linalg.norm(a,1) L2=np.linalg.norm(a,2) print(L1) print(L2)
a=['first','second'] for index, item in enumerate(a): print(index) print(item)
import numpy as np import matplotlib.pyplot as plt a=[5,7,3,4,5] #by default there are gonna be 10 bins his,bins=np.histogram(a) #print(his) #print(bins) plt.hist(his,bins) plt.show() his,bins=np.histogram(a,density=True) plt.hist(his,bins) plt.show() his.bins=np.histogram(a,bins=[3,4,5,6,7],density=True) plt.hist(his,bins) plt.show()
import numpy as np x=np.array([8,1,3,5,2,9,6,4]) index=np.argsort(x) print(x) #argsort result in the index in ascending order print(index)
def wrap(string, max_width): chars = [] output = "" i = 0 j = max_width while j < len(string)+max_width : chars.append(string[i:j]) i += max_width j += max_width for i in chars: if chars.index(i) != len(chars)-1: output += (i + "\n") else: output += (i) return output if __name__ == '__main__': string = input("Enter a string : ") max_width = int(input("To how much characters do you want to wrap ? ")) result = wrap(string, max_width) print(result)
f = raw_input('Enter file name :') fhand = open(f, "r") text = fhand.read() words = text.split() newDict = dict() for word in words: newDict[word] = None print newDict g = raw_input('Enter Key value :') print g in newDict
def listNumber(): b = 0 empList = [] while True: a = raw_input('Enter the number : ') if a == 'done': floatList = map(float, empList) print 'Maximum : ', max(floatList), "Minimum : ", min(floatList) break else: try: #b += float(a) empList.append(a) except: print('Invalid Input') listNumber()
file1 = raw_input('Enter the file name: ') def fileName(file1): fh = open(file1, "r") el = [] for line in fh: f = line.split() el.extend(f) el.sort() print el fileName(file1)
""" // Time Complexity : o(n) // Space Complexity : o(n), dictionary // Did this code successfully run on Leetcode : yes // Any problem you faced while coding this : no // Your code here along with comments explaining your approach """ from collections import defaultdict """ # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random """ class Solution: def copyRandomList(self, head: 'Node') -> 'Node': if not head : return None d = defaultdict(Node) #for mapping original list to copy copy = Node(head.val) #creating copy of the head cur = head #cur ptr to iterate d[head] = copy #mapping of head while cur: if cur.random: #if cur has a random ptr if cur.random not in d: #if copy hasnt been created yet, create node and add to dictionary d[cur.random] = Node(cur.random.val) copy.random = d[cur.random] #create copy of node if cur.next: if cur.next not in d: #similarly for next pointer d[cur.next] = Node(cur.next.val) copy.next = d[cur.next] cur = cur.next #increment copy = copy.next return d[head]
from turtle import * import turtle speed(0) bgcolor("black") pensize(3) for x in range (5): for colors in ["red","pink","blue","cyan","green","yellow","white"]: color(colors) left(12) for i in range(4): forward(200) left(90) turtle.done()
import turtle turtle.title("@happy_coding") s = turtle.Screen() t = turtle.Turtle() def move_to(x,y): t.penup() t.goto(x,y) t.pendown() def draw_rectangle(a,b): t.begin_fill() t.forward(a) t.left(90) t.forward(b) t.left(90) t.forward(a) t.left(90) t.forward(b) t.end_fill() t.speed(10) t.color("red") move_to(-500,200) draw_rectangle(10,100) move_to(-490,250) t.left(90) draw_rectangle(80,10) move_to(-410,200) t.left(90) draw_rectangle(10,100) move_to(-380,200) t.left(60) t.color("yellow") draw_rectangle(10,122) move_to(-275,198) t.left(145) draw_rectangle(10,110) move_to(-350,230) t.left(335) draw_rectangle(10,63) move_to(-240,198) t.left(270) t.color("green") draw_rectangle(100,10) move_to(-240,288) draw_rectangle(50,10) move_to(-190,288) draw_rectangle(40,10) move_to(-190,248) draw_rectangle(50,10) move_to(-160,198) t.color("violet") draw_rectangle(100,10) move_to(-160,288) draw_rectangle(50,10) move_to(-110,288) draw_rectangle(40,10) move_to(-110,248) draw_rectangle(50,10) move_to(-80,198) t.left(320) t.color("orange") draw_rectangle(120,10) move_to(-100,295) draw_rectangle(68,10) move_to(-500,80) t.left(40) t.color("blue") draw_rectangle(100,10) t.left(180) move_to(-490,70) draw_rectangle(50,10) t.left(90) t.fd(50) t.right(90) draw_rectangle(80,10) t.left(90) t.fd(80) t.left(270) draw_rectangle(50,10) move_to(-400,80) t.left(180) t.color("pink") draw_rectangle(100,10) move_to(-220,70) t.left(60) t.color("brown") draw_rectangle(100,10) t.left(300) move_to(-370,70) t.right(152) draw_rectangle(100,10) t.left(152) move_to(-290,10) t.right(45) draw_rectangle(40,10) t.right(3) draw_rectangle(40,10) move_to(-200,-15) t.left(200) t.color("darkgreen") draw_rectangle(10,110) move_to(-95,-20) t.left(145) draw_rectangle(10,114) move_to(-175,25) t.left(333) draw_rectangle(10,63) move_to(-70,79) t.left(90) t.color("skyblue") draw_rectangle(101,10) move_to(-60,-22) t.left(180) draw_rectangle(80,10) move_to(50,-22) t.left(180) t.color("black") draw_rectangle(100,10) move_to(300,150) t.color("red") angle=0 for i in range(20): t.fd(50) move_to(300,150) angle+=18 t.left(angle) move_to(450,150) t.color("blue") angle=0 for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(450,150) move_to(375,300) t.color("green") angle=0 for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(375,300) move_to(375,-300) t.color("black") angle=0 for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(375,-300) move_to(150,-150) t.color("violet") angle=0 for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(150,-150) move_to(450,-150) t.color("brown") angle=0 for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(450,-150) move_to(-200,-300) t.color("green") angle=0 for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(-200,-300) move_to(125,0) t.color("yellow") angle=0 for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(125,0) t.color("pink") angle=0 move_to(-100,-200) for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(-100,-200) t.color("lightgreen") angle=0 move_to(300,0) for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(300,0) t.color("skyblue") angle=0 move_to(-500,-240) for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(-500,-240) t.color("orange") angle=0 move_to(-350,-170) for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(-350,-170) t.color("black") angle=0 move_to(500,20) for i in range(20): t.fd(50) angle+=18 t.left(angle) move_to(500,20) turtle.done()