text
stringlengths
37
1.41M
#1 Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". #Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5] def big(list): newlist = [] for x in range(0,len(list)): if list[x] > 0: newlist.append("big") else: newlist.append(list[x]) continue return newlist print(big([-1,3,5,-5])) #2 Count Positives - Given a list of numbers, create a function to replace the last value with the number of positive values. (Note that zero is not considered to be a positive number). #Example: count_positives([-1,1,1,1]) changes the original list to [-1,1,1,3] and returns it #Example: count_positives([1,6,-4,-2,-7,-2]) changes the list to [1,6,-4,-2,-7,2] and returns it def positives(list): positive = 0 for x in range(0,len(list)): if list[x] > 0: positive += list[x] list.pop(-1) list.append(positive) return list print(positives([-1,1,1,1])) print(positives([1,6,-4,-2,-7,-2])) #3 Sum Total - Create a function that takes a list and returns the sum of all the values in the array. #Example: sum_total([1,2,3,4]) should return 10 #Example: sum_total([6,3,-2]) should return 7 def sum(list): total = 0 for x in range(0,len(list)): total += list[x] return total print(sum([1,2,3,4])) print(sum([6,3,-2])) #4 Average - Create a function that takes a list and returns the average of all the values. #Example: average([1,2,3,4]) should return 2.5 def average(list): total = 0 for x in range(0,len(list)): total += list[x] return total / len(list) print(average([1,2,3,4])) #5 Length - Create a function that takes a list and returns the length of the list. #Example: length([37,2,1,-9]) should return 4 #Example: length([]) should return 0 def length(list): return len(list) print(length([37,2,1,-9])) print(length([])) #6 Minimum - Create a function that takes a list of numbers and returns the minimum value in the list. If the list is empty, have the function return False. # Example: minimum([37,2,1,-9]) should return -9 # Example: minimum([]) should return False def minimum(list): if list == []: return False else: minimum = list[0] for x in range (1,len(list)): if list[x] < minimum: minimum = list[x] return minimum print(minimum([37,2,1,-9])) print(minimum([])) #7 Maximum - Create a function that takes a list and returns the maximum value in the array. If the list is empty, have the function return False. #Example: maximum([37,2,1,-9]) should return 37 #Example: maximum([]) should return False def maximum(list): if list == []: return False else: maximum = list[0] for x in range(0,len(list)): if list[x] > maximum: maximum = list[x] return maximum print(maximum([37,2,1,-9])) #8 Ultimate Analysis - Create a function that takes a list and returns a dictionary that has the sumTotal, average, minimum, maximum and length of the list. #Example: ultimate_analysis([37,2,1,-9]) should return {'sumTotal': 31, 'average': 7.75, 'minimum': -9, 'maximum': 37, 'length': 4 } def ultiA(list): sumTotal = list[0] minimum = list[0] maximum = list[0] length = len(list) for x in range(1,len(list)): sumTotal += list[x] if list[x] < minimum: minimum = list[x] if list[x] > maximum: maximum = list[x] average = sumTotal / len(list) thisdict = { "sumTotal": sumTotal, "average": average, "minimum": minimum, "maximum": maximum, "length": length } return thisdict print(ultiA([37,2,1,-9])) #9 Reverse List - Create a function that takes a list and return that list with values reversed. Do this without creating a second list. (This challenge is known to appear during basic technical interviews.) #Example: reverse_list([37,2,1,-9]) should return [-9,1,2,37] def reverse(list): lastI = len(list)-1 #2nd to last int for x in range(0, int(len(list)/2)): temp = list[x] #stores current value of x in array list[x] = list[lastI-x] #changes current array value with temp/2nd to last int list[lastI-x] = temp #changes return list print(reverse([37,2,1,-9]))
class Product: def __init__(self, name, price, category): self.name = name self.price = price self.category = category self.store = Store(name) def update_price(self, percent_change, is_increased): if is_increased == True: self.price += self.price * percent_change if is_increased == False: self.price -= self.price * percent_change return self def print_into(self): print(self.name) print(self.category) print(self.price) return self class Store: def __init__(self, name): self.name = name self.product = [] # self.product = Product(name) def add_product(self, new_product): self.product.append(new_product) return self def sell_product(self, id): self.product.pop(id) return self def print_info(self): # create for loop to access each index in array to print info inside of product print(self.product) return self def inflation(self, percent_increase): self.Product.price += self.Product.price * percent_increase target = Store("target") wii = Product("wii", 100, "toy") target.add_product(wii) bestbuy = Store("bestbuy") ps3 = Product("ps3", 200, "toy") bestbuy.add_product(ps3).print_info()
#1 Update Values in Dictionaries and Lists x = [ [5,2,3], [10,8,9] ] students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } z = [ {'x': 10, 'y': 20} ] x[1][0] = 15 #1a Change the value 10 in x to 15. Once you're done, x should now be [ [5,2,3], [15,8,9] ]. x[1][0] = 15 #1b Change the last_name of the first student from 'Jordan' to 'Bryant' students[0]['last_name'] = 'Bryant' #1c In the sports_directory, change 'Messi' to 'Andres' sports_directory['soccer'][0] = 'Andres' #1d Change the value 20 in z to 30 z[0]['y'] = 30 #2 Iterate Through a List of Dictionaries #Create a function iterateDictionary(some_list) that, given a list of dictionaries, the function loops through each dictionary in the list and prints each key and the associated value. For example, given the following list: students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] #2 should output: (it's okay if each key-value pair ends up on 2 separate lines; def iterateDictionary(dict): for person in students: #declares variable person and runs loop in declared dictionary for a, b in person.items(): #loops through all keys and values in loop print('{}: {}'.format(a,b)) #{} places declared value within '()' iterateDictionary(students) # bonus to get them to appear exactly as below!) first_name - Michael, last_name - Jordan first_name - John, last_name - Rosales first_name - Mark, last_name - Guillen first_name - KB, last_name - T #3 Get Values From a List of Dictionaries #Create a function iterateDictionary2(key_name, some_list) that, given a list of dictionaries and a key name, the function prints the value stored in that key for each dictionary. For example, iterateDictionary2('first_name', students) should output: def iterateDictionary2(key_name, some_list): for v in students: #declares variable person and runs for loop in dictionary print('{}'.format(v[key_name])) #{} places first declared value within '()' iterateDictionary2('first_name',students) #key_name = 'first_name' #calling list 'students' iterateDictionary2('last_name', students) #4 Iterate Through a Dictionary with List Values # Create a function printInfo(some_dict) that given a dictionary whose values are all lists, prints the name of each key along with the size of its list, and then prints the associated values within each key's list. For example: dojo = { 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'], 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon'] } def printInfo(some_dict): for k, v in some_dict.items(): print(len(v)) for x in v: print(x) printInfo(dojo)
class BankAccount: def __init__(self, name): self.name = name self.balance = 0 self.interest_rate = 0.05 def deposit(self, balance): self.balance += balance return self def withdraw(self, balance): if (self.balance - balance) < 0: print('Insufficient funds: Charging a $5 fee') self.balance -= 5 else: self.balance -= balance return self def display_account_info(self): print('Balance: $',self.balance) return self def yield_interest(self): if self.balance > 0: self.balance += self.balance * self.interest_rate return self class User: def __init__(self, name, email): self.name = name self.email = email self.account = BankAccount(name) return def example_method(self): self.account.deposit(100) print(self.account.balance) return def deposit(self,amount): self.account.deposit(amount) return self def withdraw(self, balance): if (self.account.balance - balance) < 0: print('Insufficient funds: Charging a $5 fee') self.account.balance -= 5 else: self.account.balance -= balance return self def display_account_info(self): print('Balance: $',self.account.balance) return self # Ron = BankAccount("Ron") # Shaq = BankAccount("Shaq") # Ron.deposit(100).deposit(100).deposit(100).withdraw(1000).yield_interest().display_account_info() # Shaq.deposit(1000).deposit(1000).withdraw(50).withdraw(50).withdraw(50).withdraw(50).yield_interest().display_account_info() Ron = User("Ron","ron@email") Ron.deposit(100).withdraw(150).display_account_info()
# 3.写函数,参数为int,在屏幕上输出其: 10 进制,2进制、8进制、16 进制形式 a = int(input("请输入想要转换的数字:")) def transform(num): print("10进制形式:"+"\t"+str(int(num))) print("2进制形式:"+"\t"+str(bin(num))) print("8进制形式:"+"\t"+str(oct(num))) print("16进制形式:"+"\t"+str(hex(num))) transform(a)
class Solution: # @param {string} s # @return {string} def longestPalindrome(self, s): def isPalindrome(s): #s = "".join(map(lambda c: c.lower(), filter(lambda c: c.isalnum(), s))) L = len(s) mid = int(L/2) if L % 2 == 0: return s[:mid] == s[-1:-mid-1:-1] else: return s[:mid] == s[-1:-mid-1:-1] L = len(s) max_len = 0 if isPalindrome(s): return s for i in range(L): for w in range(min(i+1, L-i+1)): s_odd = s[i-w:i+w+1] s_even = s[i-w:i+w] if isPalindrome(s_odd): if max_len < 2*w + 1: max_s, max_len = s_odd, 2*w + 1 else: if isPalindrome(s_even): if max_len < 2*w: max_s, max_len = s_even, 2*w else: break return max_s if __name__ == "__main__": solu = Solution() s = "abababababa" print(solu.longestPalindrome(s))
""" Read file into texts and calls. It's ok if you don't understand how to read files """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 2: Which telephone number spent the longest time on the phone during the period? Don't forget that time spent answering a call is also time spent on the phone. Print a message: "<telephone number> spent the longest time, <total time> seconds, on the phone during September 2016.". """ spendTimeOnPhone = {} for call in calls: if spendTimeOnPhone.get(call[0]) == None: spendTimeOnPhone[call[0]] = int(call[3]) else: spendTimeOnPhone[call[0]] += int(call[3]) if spendTimeOnPhone.get(call[1]) == None: spendTimeOnPhone[call[1]] = int(call[3]) else: spendTimeOnPhone[call[1]] += int(call[3]) #maxTime = 0 #maxCallNum = '' ##spendTimeOnPhone ##print(spendTimeOnPhone) # #for call in spendTimeOnPhone: # if spendTimeOnPhone[call] > maxTime: # maxTime = spendTimeOnPhone[call] # maxCallNum = call #print(spendTimeOnPhone) longest_duration = max(spendTimeOnPhone.items(), key=lambda x: x[1]) #print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(maxCallNum, maxTime)) print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(*longest_duration))
print("Hello. This program converts kilometers into miles.") repeat = None while True: km = int(input("Enter number of kilometers: ")) mi = km * 0.621371 print(mi) repeat = str(input('Do you want to do another conversion? Type "yes" or "no": ')) if repeat != "yes": print("Thank you, goodbye.") break
wrd = input("Enter a word: ") if wrd == wrd[::-1]: print(wrd, "is a pallindrome") else: print(wrd, "is not a pallindrome") input("Press Enter key to exit")
from sqlalchemy import MetaData, Table, Column, String, Integer, ForeignKey, create_engine from sqlalchemy.sql import select engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String(100), nullable=False), Column('fullname', String(50), nullable=False) ) addresses = Table('addresses', metadata, Column('id', Integer, primary_key=True), Column('email_address', String(100), nullable=False), Column('user_id', Integer, ForeignKey('users.id'), nullable=False) ) metadata.create_all(engine) conn = engine.connect() conn.execute(users.insert().values(name='jack',fullname='nyoman pradipta')) conn.execute(addresses.insert(), [ {'user_id': 1, 'email_address': 'jack@yahoo.com'}, {'user_id': 1, 'email_address': 'jack@msn.com'}, ]) """ The MetaData object contains all of the schema constructs we’ve associated with it. It supports a few methods of accessing these table objects, such as the sorted_tables accessor which returns a list of each Table object in order of foreign key dependency (that is, each table is preceded by all tables which it references): """ print([x.name for x in metadata.sorted_tables]) # access the column "ID": print(users.columns.id) # or just print(users.c.id) # via string print(users.c['id']) # iterate through all columns print([x for x in users.c]) # get the table's primary key columns print([x for x in users.primary_key]) # get the table's foreign key objects: print([x for x in addresses.foreign_keys]) # get the table related by a foreign key print(list(addresses.c.user_id.foreign_keys)[0].column.table.c.name) s = select([addresses,users]).where(addresses.c.email_address == 'jack@yahoo.com').select_from(addresses.join(users)) print(s) print(conn.execute(s).fetchone().name)
from define_create_table import users, addresses from create_query import conn from sqlalchemy.sql import select, func stmt = select([users.c.name]).order_by(users.c.name) print(conn.execute(stmt).fetchall()) print() """ Ascending or descending can be controlled using the ColumnElement.asc() and ColumnElement.desc() modifiers: """ stmt = select([users.c.name]).order_by(users.c.name.desc()) print(conn.execute(stmt).fetchall()) print() """ Grouping refers to the GROUP BY clause, and is usually used in conjunction with aggregate functions to establish groups of rows to be aggregated. This is provided via the SelectBase.group_by() method: """ stmt = select([users.c.name, func.count(addresses.c.user_id)]).select_from(users.join(addresses)).group_by(users.c.name) print(conn.execute(stmt).fetchall()) print() """ HAVING can be used to filter results on an aggregate value, after GROUP BY has been applied. It’s available here via the Select.having() method: """ stmt = select([users.c.name, func.count(addresses.c.user_id)]).select_from(users.join(addresses)) \ .group_by(users.c.name).having(func.length(users.c.name) > 4) print(conn.execute(stmt).fetchall()) print() """ The Select.limit() and Select.offset() methods provide an easy abstraction into the current backend’s methodology: """ stmt = select([users.c.name, addresses.c.email_address]).select_from(users.join(addresses)) \ .limit(1).offset(1) print(conn.execute(stmt).fetchall()) print()
""" The Union type allows a model attribute to accept different types, e.g.: """ from pydantic import BaseModel from uuid import UUID from typing import Union class User(BaseModel): id: Union[int, str, UUID] name: str user_01 = User(id=123, name='John Doe') print(user_01) # > id=123 name='John Doe' print(user_01.id) # > 123 user_02 = User(id='1234', name='John Doe') print(user_02) # > id=1234 name='John Doe' print(user_02.id) # > 1234 user_03_uuid = UUID('cf57432e-809e-4353-adbd-9d5c0d733868') user_03 = User(id=user_03_uuid, name='John Doe') print(user_03) # > id=275603287559914445491632874575877060712 name='John Doe' """ However, as can be seen above, pydantic will attempt to 'match' any of the types defined under Union and will use the first one that matches. In the above example the id of user_03 was defined as a uuid.UUID class (which is defined under the attribute's Union annotation) but as the uuid.UUID can be marshalled into an int it chose to match against the int type and disregarded the other types. As such, it is recommended that, when defining Union annotations, the most specific type is included first and followed by less specific types. In the above example, the UUID class should precede the int and str classes to preclude the unexpected representation as such: """
class seat(): def __init__(self , x, y): self.x = x self.y = y def is_seat_valid(self): if self.x < 9 and self.x > 0 and self.y < 9 and self.y > 0: return True else: return False def get_x(self): return self.x def get_y(self): return self.y def show(self): print("(" + str(self.x) + "," + str(self.y) + ")") valid_seats = [ seat(1,1),seat(1,2),seat(1,4),seat(1,5),seat(1,6),seat(1,8), seat(2,1),seat(2,2),seat(2,4),seat(2,5),seat(2,6),seat(2,8), seat(3,1),seat(3,2),seat(3,3),seat(3,4),seat(3,7),seat(3,8), seat(4,1),seat(4,5),seat(4,6),seat(4,7),seat(4,8), seat(5,1),seat(5,2),seat(5,3),seat(5,5),seat(5,6),seat(5,7),seat(5,8), seat(6,1),seat(6,3),seat(6,4),seat(6,5),seat(6,7),seat(6,8), seat(7,1),seat(7,5),seat(7,8), seat(8,2),seat(8,3),seat(8,4),seat(8,5),seat(8,6),seat(8,7),seat(8,8)] def check_if_contain(seat_step, valid_seats): for valid_seat in valid_seats: if seat_step.get_x() == valid_seat.get_x() and seat_step.get_y() == valid_seat.get_y(): return True return False def seat_add(start, step): return seat(start.get_x()+ step.get_x(), start.get_y() + step.get_y()) def new_step_seat(valid_seats, searched_seats, start, seat_steps): for seat_step in seat_steps: new_seat = seat_add(start, seat_step) if check_if_contain(new_seat, valid_seats): if check_if_contain(new_seat, searched_seats) == False: return new_seat return None def mazepath(valid_seats,start,end): solution_path = [] searched_seats = [] solution_path.append(start) searched_seats.insert(0, start) seat_steps = [seat(0,1),seat(1,0),seat(0,-1),seat(-1,0)] while check_if_contain(end, solution_path) == False and len(solution_path) > 0: start_seat = solution_path[-1] #start_seat.show() new_start_seat = new_step_seat(valid_seats, searched_seats, start_seat, seat_steps) if new_start_seat!= None: print("new_start_seat ( " + str(new_start_seat.get_x())+ "," + str(new_start_seat.get_y())+ ")") solution_path.append(new_start_seat) searched_seats.insert(0, new_start_seat) else: seat_pop = solution_path.pop() print("solution_path.pop() ( " + str(seat_pop.get_x())+ "," + str(seat_pop.get_y())+ ")") return solution_path start = seat(1,1) end = seat(8,8) mazepaths = mazepath(valid_seats, start, end) for mazepath in mazepaths: mazepath.show()
a = 2 b = 2 c = "txt" d = "txt" print("a = " + str(a)) # ตัวแปรต่างชนิดกัน print("b = " + str(b)) print(a+b) print("c + d = " + c + d) # string + string คือ ข้อความต่อกัน a = b = 2 # การกำหนดแบบลูกโซ่ c = d = "txt" print("a = " + str(a)) print("b = " + str(b)) print(a+b) print("c + d = " + c + d)
# This solution belongs to user https://www.codingame.com/profile/8fe6daf329d120f0e3014777bebfec313384001 # User Ryba published it over 1 year ago import sys import math surface_n = int(raw_input()) # the number of points used to draw the surface of Mars. x1 = x2 = yr = 0 f = False for i in xrange(surface_n): land_x, land_y = [int(j) for j in raw_input().split()] if land_y == yr: x2 = land_x f = True if not f: x2 = x1 x1 = land_x yr = land_y xl = (x1 + x2)/2 # game loop while 1: # h_speed: the horizontal speed (in m/s), can be negative. # v_speed: the vertical speed (in m/s), can be negative. # fuel: the quantity of remaining fuel in liters. # rotate: the rotation angle in degrees (-90 to 90). # power: the thrust power (0 to 4). x, y, h_speed, v_speed, fuel, rotate, power = [int(i) for i in raw_input().split()] print >> sys.stderr, yr lim = 25*abs(2*xl-x)/xl sig = -1 if x<xl else 1 if x<x1 or x>x2: rot = 30*(h_speed+sig*lim)/45 if v_speed < -10 or y-yr<250: pow = 4 else: pow = 2 else: if abs(h_speed) > 5: rot = (h_speed) else: rot = 0 if y - yr < 50: rot = 0 if v_speed < -20: pow = 4 else: pow = 0 print rot, pow
''' This file is not an actual blockchain. It's hardcoded Python that I used to prepare the design of the actual app which could be found in /py-blockchain/app.py You can run this in your terminal to play around with it as well. ''' # create users class class Users: def __init__(self, address, key, id, wallet_id): self.address = address self.key = key self.id = id self.wallet_id = wallet_id def transactor(self): print("Your transaction is in progress...") # create user object : user1 = Users("a1", "k1", "i1", "w1") # test out transactions print("Hello, enter the address for the person you will be sending a transaction to ") info = input("Address: ") if(info != user1.address): print("Sorry, a user with that address cannot be found. Please enter a new address to try again : ") info = input("Address: ") amount = input("Amount: ") print("You will be sending " + amount + " to user " + info + ". Is this correct? ") confirm = input(" Y / N : ") if(confirm == "Yes" or confirm == "yes"): user1.transactor() print("You have successfully sent " + amount + " to " + info)
from molmass import Formula RawData = input("Gas Formula, to second Gas, ratio, x for unknown: ") while(RawData != "quit"): SplitData = RawData.split(" ") F0 = SplitData[0] F = Formula(F0) R = float(SplitData[1]) print("Results: x = ", F.mass/(R**2)) RawData = input("Gas Formula, Mass, Temp(C), Volume, Pressure, x for unknown: ")
import numpy as np import matplotlib.pyplot as plt x = np.arange(-3,3,0.01) y = (x**4)-(2*(x**2))+(11*x)-6.1 fx = lambda x : (x**4)-(2*(x**2))+(11*x)-6.1 # x0=float(input("Masukkan x0: ")) # x1=float(input("Masukkan x1: ")) Es = 0.0001 Er = 100.0 x1 = 2.75 x0 = 1 i = 0 if(x0!=0): print("Iterasi\t Xn-1\t\t Xn \t\t Xn+1 \t\t F(Xn-1) \t F(Xn) \t\t F(Xn+1) \t Er") while abs(Er)>0.1: xn = x1 -((fx(x1)*(x1-x0))/(fx(x1)-fx(x0))) Er = ((xn-x0)/xn)*100 print ("%d\t %f\t %f\t %f\t" "%f\t %f"%(i,x0,x1,xn,fx(xn),abs(Er))) x0 = x1 x1 = xn i+=1 print("Root : %f" % (xn)) else: print("Penentuan xn salah")
import tkinter as tk root = tk.Tk() root.title('Find and Replace') tk.Label(root, text="Find: ").grid(row=0, column=0, sticky=tk.E) tk.Entry(root, width=60).grid(row=0, column=1, padx=2, pady=2, sticky=tk.W + tk.E, columnspan=9) tk.Label(root, text="Replace: ").grid(row=1, column=0, sticky=tk.E) tk.Entry(root, width=60).grid(row=1, column=1, padx=2, pady=2, sticky=tk.W + tk.E, columnspan=9) tk.Button(root, text="Find").grid(row=0, column=10, sticky=tk.E+tk.W, padx=2, pady=2) tk.Button(root, text="Find All").grid(row=1, column=10, sticky=tk.E+tk.W, padx=2, pady=2) tk.Button(root, text="Replace").grid(row=2, column=10, sticky=tk.E+tk.W, padx=2, pady=2) tk.Button(root, text="Replace All").grid(row=3, column=10, sticky=tk.E+tk.W, padx=2, pady=2) tk.Checkbutton(root, text="Match Whole Word Only").grid(row=2, column=1, columnspan=4, sticky=tk.W) tk.Checkbutton(root, text="Match Case").grid(row=3, column=1, columnspan=4, sticky=tk.W) tk.Checkbutton(root, text="Wrap Around").grid(row=4, column=1, columnspan=4, sticky=tk.W) tk.Label(root, text="Direction: ").grid(row=2, column=3, columnspan=4, sticky=tk.E) tk.Radiobutton(root, text="up", value=1).grid(row=3, column=4, columnspan=4, sticky=tk.E) tk.Radiobutton(root, text="down", value=2).grid(row=3, column=5, columnspan=2, sticky=tk.E) root.mainloop()
#!/usr/bin/env python from Word_Counter import * def test_word_counter(): """ >>> wc = Word_Counter() >>> sent = "Once upon a midnight dreary while I pondered weak and weary " >>> sent += "over many a quaint and curious volume of forgotten lore" >>> for word in sent.split(): wc.count(word) >>> wc.get_count("Once") 1 >>> wc.get_count("a") 2 >>> wc.get_count("Lenore") 0 """ def test_sort_words(): """ >>> wc = Word_Counter() >>> sent = "And I was like baby baby baby oh " >>> sent += "Like baby baby baby oh " >>> sent += "I though you'd always be mine mine " >>> for word in sent.split(): wc.count(word) >>> wc.sort_words(['I', 'baby', 'always', 'yes']) ['baby', 'I', 'always', 'yes'] """ if __name__=='__main__': import doctest doctest.testmod()
# -*- coding: utf-8 -*- # 20200213 by sangkny # y2img : convert y image to normal format # y2img(in_y_file, out_imgfile, img_height=40, img_width=32, debug_general = True) # binary file i/o example import os import numpy as np import cv2 def y2img(in_y_file, out_imgfile, img_height=40, img_width=32, debug_general = True, img_quality=100): file_height, file_width, file_debug = img_height, img_width, debug_general num_channels = 0 if os.path.isfile(in_y_file): f = open(in_y_file, 'rb') #lines = f.readlines() lines = f.read() #indices = range(len(lines[0])) # when open with rt and f.readlines() -> list output indices = range(len(lines)) if int(file_height*file_width) == len(lines): # gray num_channels = 1 if(debug_general): print('this 1 channel : h x w:{}x{}'.format(file_height, file_width)) elif int(file_height*file_width*3) == len(lines): # B/G/R 3 channels num_channels = 3 if (debug_general): print('B/G/R 3 channel : h x w x 3:{}x{}x 3'.format(file_height, file_width)) else: print('\n ---------------> error <---------------\n') print('file size is not correct: %s \n'% in_y_file) return 0 if num_channels>1: img_nparray = np.zeros([file_height, file_width, num_channels], dtype='uint8') else: img_nparray = np.zeros([file_height, file_width], dtype='uint8') for i in indices: idx_row = int(i/file_width) # it has row and channel information idx_ch = int(idx_row/file_height) # channel number [0 num_channels-1] idx_row %= file_height # converts only for image rows [0 file_height-1] idx_col = i%file_width # converst only for image cols [0 file_width-1] if(debug_general and (idx_ch==0 and idx_col == 0 and idx_row == 0)): print("(row x col x ch: {}x{}x{})->({}) \n".format(idx_row,idx_col,idx_ch, lines[i])) if num_channels> 1: img_nparray[idx_row][idx_col][idx_ch] = lines[i] else: # 1 channel img_nparray[idx_row][idx_col]= lines[i] f.close() # need to convert B/G/R to R/G/B with channel swaps for processing. # however, if you want to write the image as RGB format using opencv , the order of channels should be # B/G/R. Then opencv write a file with the order of RGB # cv2.cvtColor(img_nparray,cv2.COLOR_BGR2RGB, img_nparray) if(debug_general): cv2.imshow('test', img_nparray) cv2.waitKey(1) if not cv2.imwrite(out_imgfile, img_nparray, [int(cv2.IMWRITE_JPEG_QUALITY), int(img_quality)]): print('Writing Error: %s' %out_imgfile) else: print('File No Exists: %s' %in_y_file)
#Author: Jiang Wei #装饰器:本质是函数,(装饰其他函数)就是为其它函数添加附加功能 '''原则:不能修改被装饰函数的源代码,不能修改被装饰函数的调用方式''' ''' def foo(): print("in the foo") bar() def bar(): print("in the bar") 这一段代码可以正常运行,因为调用foo之前foo跟bar都已经声明并且已经在内存中存好 foo() ''' ''' def foo(): print("in the foo") bar() foo() def bar(): print("in the bar") 这一段代码不可以正常运行,报错,因为调用foo之前bar还没有声明在内存中找不到,因此可以证明 函数即变量,它只是声明好了你不调用它就不会运行,你调用时才会去找对应的内存 def foo(fun): start_time = time.time() print("-------") fun() print("++++++++") stop_time = time.time() print("运行时间%s"%(stop_time-start_time)) return fun @foo #bar = foo(bar) def bar(): time.sleep(3) print("in the bar") bar()#未修改bar函数的源码但是给它添加了新功能 ''' ''' #这是一个真正的装饰器 但是并不完美,因为如果有带参数的函数时就不能装饰 import time def timer(func): def deco(): start_time = time.time() print(func) func() stop_time = time.time() return deco @timer #他的作用是在后面test2函数后面隐实的加上 test2 = timer(test2),因此真正运行的是deco # 这个函数,test2这个函数被放在deco里面去运行了 def test2(): time.sleep(2) print("in the test2") #test2 = timer(test2) test2() print(test2)#它们的内存地址都不一样 #装饰器的使用场景 即你的函数已经写好已经上线,在你不能修改源代码的情况之下给这个函数 # 添加功能 ''' #这是一个完美的装饰器 可以装饰任何有参没参的函数 import time def timer(func): def deco(*args,**kwargs): start_time = time.time() print(func) func(*args,**kwargs) stop_time = time.time() return deco @timer #他的作用是在后面test2函数后面隐式的加上 test2 = timer(test2),因此真正运行的是deco # 这个函数,test2这个函数被放在deco里面去运行了 def test2(): time.sleep(2) print("in the test2") #test2 = timer(test2) test2() print(test2)#它们的内存地址都不一样 @timer def test3(name,x,z): print(name,x,z) #test3 = timer(test3) test3("jw",30,"m") #装饰器的使用场景 即你的函数已经写好已经上线,在你不能修改源代码的情况之下给这个函数 # 添加功能
class hospital (object): def __init__(self,name,capacity,*patients): self.patients = list(patients) self.name = name self.capacity = capacity - len(self.patients) def info(self): print self.name names = "" for x in range(0,len(self.patients)): names += str(self.patients[x].ids) names += " " names += self.patients[x].name names += " " names += str(self.patients[x].bed) names += ", " print names print self.capacity
def draw_stars(x): for i in range(0,len(x)): string = "" isInt = isinstance(x[i],int) isStr = isinstance(x[i],str) if isInt == True: for j in range(1,x[i]+1): string += "*" elif isStr == True: for j in range(0,len(x[i])): string += x[i][0] print string x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"] draw_stars(x)
# function input my_dict = [ {"Speros": "(555) 555-5555"}, {"Michael": "(999) 999-9999"}, {"Jay": "(777) 777-7777"} ] # function output # [("Speros", "(555) 555-5555"), ("Michael", "(999) 999-9999"), ("Jay", "(777) 777-7777")] def dictTup (my_dict): my_tuple = [] for x in range(0,len(my_dict)): my_tuple.append(my_dict[x]) print (my_tuple) dictTup(my_dict) print (my_dict[0])
#//-------------------------------------------------------------------------------------------- #// set_methods #//-------------------------------------------------------------------------------------------- ''' set={"app","telsuko","learning"} set.add("phone") print(set) ''' ''' set={"app","telsuko","learning"} set1=["app","telsuko"] set.update(set1) print(set) ''' ''' set={"app","telsuko","learning"} set1=["phone"] z=set.union(set1) print(z) ''' ''' set={"app","telsuko","learning"} set.remove("telsuko") print(set) ''' set={"app","telsuko","learning"} set.discard("app") print(set)
import pandas as pd rep=0 fields=['Name','Admission number','Roll number','Class','Science marks','Maths marks','Sst marks','English marks'] def menu(): print('1. Add new student data : ') print('2.Display marksheet : ') print('3.Compute ranks : ') print('4.Merit students : ') print('5.Exit : ') def new(): global fields global rep data=[] for i in fields: val=input('Enter '+ i + ': ') data.append(val) if rep==0: df=pd.DataFrame([[data[i] for i in range(len(data))]],columns=['Name','Admission Number','Roll Number','Class','Science Marks','Maths Marks','SST Marks','English Marks']) df.to_csv('student_data.csv',mode='a',index=False) else: df=pd.DataFrame([[data[i] for i in range(len(data))]],columns=['Name','Admission Number','Roll Number','Class','Science Marks','Maths Marks','SST Marks','English Marks']) df.to_csv('student_data.csv',mode='a',index=False,header=0) print('DATA SAVED SUCCESSFULLY') input('Press any key to continue') return def display(): print('Through what would you like to search?') print('1.Class') print('2.Roll number') print('3.Name') imp=input('Enter the number : ') if imp=='1': cl=int(input('Enter the class : ')) df=pd.read_csv('student_data.csv') liclass=[i for i in df["Class"]] if cl in liclass: x=df.loc[df['Class']==cl] print(x) else: print('DATA NOT FOUND') elif imp=='2': rno=int(input('Enter the Roll number : ')) df=pd.read_csv('student_data.csv') lirno=[i for i in df["Roll Number"]] if rno in lirno: x=df.loc[df['Roll Number']==rno] print(x) else: print('DATA NOT FOUND') elif imp=='3': nm=input('Enter the name : ') df=pd.read_csv('student_data.csv') linm=[i for i in df["Name"]] if nm in linm: x=df.loc[df['Name']==nm] print(x) else: print('DATA NOT FOUND') else: print('ERROR!!!!! ENTER ONLY 1, 2 OR 3') input('Press any key to continue') return def compute_ranks(): df=pd.read_csv('student_data.csv') df['Aggregate Percentage']=((df['Science Marks']+df['Maths Marks']+df['SST Marks']+df['English Marks'])/4) df.to_csv('student_data.csv',index=False) print(df.sort_values('Aggregate Percentage',ascending=False)) input('Press any key to continue') return def merit_students(): df=pd.read_csv('student_data.csv') y=df.loc[df['Aggregate Percentage']>=90] x=y.sort_values('Aggregate Percentage',ascending=False) z=x.tail(len(df['Name'])) print(z.head(10)) input('Press any key to continue') return while True: menu() choice=input('Choose one of the options : ') if choice=='1': new() rep+=1 elif choice=='2': display() elif choice=='3': compute_ranks() elif choice=='4': merit_students() elif choice=='5': break else: print('ERROR!! PLEASE ENTER ONLY NUMBERS 1 TO 5') input('PRESS ANY KEY TO CONTINUE')
import arcade from . import constants class Background: """ A class representing a window background.""" def __init__(self, texture=None, color=None): # To avoid error with loading a texture with None as parameter self.texture = None if texture is None else arcade.load_texture(texture) # We don't allow both attributes at the same time self.color = color if texture is None else None def draw(self): if self.texture: arcade.draw_texture_rectangle(constants.SCREEN_WIDTH/2, constants.SCREEN_HEIGHT/2, constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT, self.texture) else: arcade.draw_rectangle_filled(constants.SCREEN_WIDTH/2, constants.SCREEN_HEIGHT/2, constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT, self.color) class StartBackground(Background): """ The background you start with, this inherits from Background.""" def __init__(self): super().__init__(texture="game/assets/start_background_base.png") class GameBackground(Background): """ The default background which is used while playing.""" def __init__(self): super().__init__(color=arcade.color.AMAZON) # MAKE FILE
#!/usr/bin/env python # Author: Epihaius # Date: 2019-10-06 # Last revision: 2020-10-08 # # This is a basic example of how to use the sizer-based GUI system. # It specifically showcases the growth of a Sizer in two directions. # Cells are always added in a specific "primary" direction, which is # either horizontal or vertical. However, by specifying a non-zero # limit to the number of cells that can be added this way, the number # of cells exceeding this limit are added to additional rows (if the # primary direction is horizontal) or columns, resulting in a grid-like # layout of its cells. from panda3d.core import * from direct.showbase.ShowBase import ShowBase from direct.gui.DirectGui import * from gui import * class MyApp: def __init__(self): # initialize the Panda3D showbase self.showbase = showbase = ShowBase() # the root node of all DirectGui widgets needs to be pixel2d in order to work # with the automatic layout system self.gui_root = gui_root = showbase.pixel2d # initialize the GUI system self.gui = gui = GUI(showbase) # Build the GUI layout # add a horizontally expanding title bar title = "Panda3D: grid layout example" label = DirectLabel(parent=gui_root, text=title, frameSize=(0, 0, -20, 30), text_scale=20, borderWidth=(6, 6), relief=DGG.SUNKEN) widget = Widget(label) borders = (10, 10, 20, 10) # by default, the title bar will take up all of the width and height of its # cell (the default value for the `alignments` parameter of the `Sizer.add` # method is `("expand", "expand")`), but the cell itself still needs to be # able to take up the entire width of the window; this is done by setting # the horizontal proportion (which gets applied to the cell's column) to a # value bigger than zero gui.sizer.add(widget, proportions=(1., 0.), borders=borders) # add a horizontal sizer that will be expanded vertically and horizontally; # setting `prim_limit` to 3 will horizontally add up to 3 cells to the sizer; # a new row will automatically be created when a 4th object is added, resulting # in a grid-like layout sizer = Sizer("horizontal", prim_limit=3, gaps=(20, 10)) borders = (10, 10, 0, 0) gui.sizer.add(sizer, proportions=(1., 1.), borders=borders) # set explicit horizontal proportions for some of the sizer columns sizer.set_column_proportion(1, 2.) sizer.set_column_proportion(2, 1.) def clear_proportions(): sizer.clear_proportions() gui.layout() text = "Clear explicit proportions" button = DirectButton(parent=gui_root, text=text, text_wordwrap=6., text_scale=20, borderWidth=(2, 2), command=clear_proportions) widget = Widget(button) sizer.add(widget) def toggle_column1_proportion(): if sizer.has_column_proportion(1): sizer.clear_column_proportion(1) else: sizer.set_column_proportion(1, 2.) gui.layout() text = "Toggle explicit column proportion" button = DirectButton(parent=gui_root, text=text, text_wordwrap=5., text_scale=20, borderWidth=(2, 2), command=toggle_column1_proportion) widget = Widget(button) sizer.add(widget, proportions=(0., 1.)) def toggle_column2_proportion(): if sizer.has_column_proportion(2): sizer.clear_column_proportion(2) else: sizer.set_column_proportion(2, 1.) gui.layout() text = "Toggle explicit column proportion" button = DirectButton(parent=gui_root, text=text, text_wordwrap=5., text_scale=15, borderWidth=(2, 2), command=toggle_column2_proportion) widget = Widget(button) sizer.add(widget, alignments=("max", "center")) def toggle_new_button(): if self.new_widget: sizer.remove_cell(self.new_widget.sizer_cell, destroy=True) self.new_widget = None toggler["text"] = "Insert n00b button" toggler.resetFrameSize() else: text = ("Hi, I'm new!", "But how?", "What's up?", "*Snooore*") button = DirectButton(parent=gui_root, text=text, text_scale=20, borderWidth=(2, 2)) self.new_widget = Widget(button) sizer.add(self.new_widget, alignments=("center", "max"), index=-1) toggler["text"] = "Remove n00b button" toggler.resetFrameSize() toggler_widget.resetFrameSize() gui.layout() toggler = DirectButton(parent=gui_root, text="Insert n00b button", text_scale=20, textMayChange=True, borderWidth=(2, 2), command=toggle_new_button) toggler_widget = Widget(toggler) sizer.add(toggler_widget, alignments=("expand", "center")) self.new_widget = None def toggle_row_proportion(): if sizer.has_row_proportion(1): sizer.clear_row_proportion(1) else: sizer.set_row_proportion(1, 3.) gui.layout() text = "Toggle explicit row proportion" button = DirectButton(parent=gui_root, text=text, text_wordwrap=5., text_scale=20, borderWidth=(2, 2), command=toggle_row_proportion) widget = Widget(button) sizer.add(widget, proportions=(0., 2.), alignments=("center", "expand")) # set an explicit vertical proportion for the bottom sizer row; it overrides # the vertical proportions associated with any cells of that row (in this # case, the proportion associated with the cell containing the last button added) sizer.set_row_proportion(1, 3.) # add a horizontally expanding status bar status_text = "GUI ready" label = DirectLabel(parent=gui_root, text=status_text, text_pos=(20, -10), textMayChange=1, frameSize=(0, 0, -10, 10), text_scale=20, text_align=TextNode.A_left) widget = Widget(label) borders = (10, 10, 10, 20) gui.sizer.add(widget, proportions=(1., 0.), borders=borders) # let the GUI system create the layout gui.layout() # run the app showbase.run() MyApp()
from typing import List import numpy as np class Generator: """Class that generates new training examples""" def __init__(self): self.best_x = 0 self.best_y = np.inf self.width = 2 def partial_fit(self, x: np.ndarray, y: float): """Add another entry""" if y < self.best_y: self.width = max(abs(self.best_x - x) * 2, 1) # Mark the increase if needed self.best_x = x self.best_y = y def generate(self, n: int) -> List[float]: """Create a set of samples Args: n (int): Number of entries to create Returns: ([float]) New samples """ return np.random.normal(self.best_x, self.width, size=(n, 1)).tolist()
a= int(input("Inrese un numero")) b= int(input("Inrese un numero")) for i in range (a,b): if i%3 == 0 and i%5 == 0: print ("FizzBuzz") elif i%5 == 0: print ("Buzz") elif i%3 == 0: print("Fizz") else: print(i)
from func.info import Info from func.purchase import Purchase username = input("Please enter your username: ") password = input("Please enter your password: ") purchasing = input("Are we purchasing stock today? Y/N: ") p = Purchase() buyStock = Purchase.purchaseQuestion(p, purchasing) # Build portfolio for program to use print("Obtaining information from Robinhood. Please wait.") info = Info(username, password) print("Portfolio Market Value: ") print("$" + str(round(info.equity, 2))) print("Highest performers: ") print(info.highPerformers) print("Lowest performers: ") print(info.lowPerformers) if len(info.highPerformersAndUnderDistributionStocks) > 0: print(info.highPerformersAndUnderDistributionStocks) else: print("There were no high performing stocks under the current distribution") print("Stocks under distribution percentage average: ") print(info.stocksUnderDistribution)
def remove_names(names): ''' Remove a name from a list. ''' removed_name = names.pop() print('Goodbye ' + removed_name.title() + '.') return names friends = ['john', 'jack', 'jill', 'james'] print(friends) new_friends = remove_names(friends.copy()) print(friends) print(new_friends) # def add_two(num): # ''' # add 2 to a number. # ''' # num += 2 # value = 10 # print(value) # value = add_two(value) # print(value) # only lists and dictionaries are mutable here. integers are immutable. # nums = [1, 2, 3, 4] # # new_nums = nums # new_nums = nums.copy() # new_nums.append(5) # print(nums) # we are pointing to the same object
# for loops : running a set number of times # while loops : running until a certain condition is met for i in range(1, 11): print(i) current_num = 1 while current_num <= 10: print(current_num) current_num += 1 current_num = 1 while True: print(current_num) current_num += 1 choice = input("Press enter to print the next number or 'q' to quit : ").lower() if choice == 'q': break
class House(): ''' a class to model a house that is for sale. ''' def __init__(self, style, sq_foot, year_built, price): ''' initialize attributes. ''' self.style = style self.sq_foot = sq_foot self.year_built = year_built self.price = price self.sold = False self.weeks_on_market = 0 def display_info(self): ''' display the information on the house. ''' print('\n-----House for Sale!-----') print('House Style:\t' + self.style) print('Square Feet:\t' + str(self.sq_foot)) print('Year Built:\t' + str(self.year_built)) print('Sale Price:\t' + str(self.price)) print('\nThis house has been on the market for ' + str(self.weeks_on_market) + ' weeks.') def sell_house(self): ''' sell the house. ''' if self.sold == False: print('Congrats! Your house has been sold for $' + str(self.price) + '.') self.sold = True else: print('Sorry, this house is no longer for sale.') def change_price(self, amount): ''' change the sale price of the house. ''' self.price += amount if amount < 0: print('Price drop!!') else: print('The house has increased in value by $' + str(amount) + '.') def update_weeks(self, weeks = 1): ''' increament the number of the weeks a house has been on the market. ''' self.weeks_on_market += weeks my_house = House('Ranch', 1800, 1962, 199000) # print out the attributes of the house print(my_house.style) print(my_house.sq_foot) print(my_house.year_built) print(my_house.price) print(my_house.sold) print(my_house.weeks_on_market) my_house.display_info() # house on market for 1 week my_house.update_weeks() my_house.display_info() # house on market for 15 week my_house.update_weeks(15) my_house.display_info() # change the sale price my_house.change_price(-15000) my_house.display_info() # house on market for 5 weeks my_house.update_weeks(5) my_house.display_info() # new interest my_house.change_price(10000) my_house.display_info() # wrong square footage my_house.sq_foot -= 150 my_house.change_price(-1000) my_house.display_info() # sell house my_house.sell_house() # someone else wants to buy the house my_house.sell_house()
print('5') print(5) print(4 + 2) print(4 - 2) print(4 * 2) print(4 / 2) print(4 ** 2) y = 4.15 print(y) y = y + 2 print(y) y += 2 print(y) y = y - 1 print(y) y -= 1 print(y)
def times_ten(x): ''' Multiply a number by 10 ''' print('Current value: ' + str(x)) x *= 10 print('Updated value: ' + str(x)) return x def char_replace(word): ''' replace specific characters in a string with other characters. ''' while 'a' in word: word = word.replace('a', '@') while 'e' in word: word = word.replace('e', '3') while 'i' in word: word = word.replace('i', '!') while 'o' in word: word = word.replace('o', '0') while 'u' in word: word = word.replace('u', '#') return word number = 3 number = times_ten(number) # print(x) # gives an error, becuase it's a local variable in the function print(number) phrase = 'hello, how are you doing today?' print(phrase) phrase = char_replace(phrase) print(phrase) # you should only makes changes to local variables inside the function # you should not makes any changes to global variables inside the function # you should not make any changes to local variables outside the function # we can use return in the function to update our global variable
name = 'Mike' age = 33 money = 9.75 # print using concatination print(name + ' is ' + str(age) + ' and has $' + str(money) + ' dollars.') # print using the .format() method for strings print("{0} is {1} and has ${2} dollars.".format(name, age, money)) # print using f-strings print(f'{name} is {age} and has ${money} dollars.')
import random print('Welcome to the Thesaurus App!') print('\nChoose a word from the thesaurus and I will give you a synonym.') thesaurus = { 'hot': ['balmy', 'summary', 'tropical', 'boiling', 'scorching'], 'cold': ['chilly', 'cool', 'freezing', 'frigid', 'polar'], 'happy': ['content', 'cheery', 'merry', 'jovial', 'jocular'], 'sad': ['unhappy', 'downcast', 'miserable', 'glum', 'melancholy'], } print('\nThese are the words in the thesaurus:') for key in thesaurus.keys(): print('\t- ' + key) word = input('\nWhat word would you like to get a synonym for? : ').lower().strip() # puzzling part :| if word in thesaurus.keys(): index = random.randint(0, 4) print('A synonym for ' + word + ' is ' + thesaurus[word][index] + '.') else: print('That word is not currently in the thesaurus.') choice = input('\nWould you like to see the whole thesaurus? (yes/no) : ').lower().strip() if choice == 'yes' or choice.startswith('y'): for key, values in thesaurus.items(): print('\n' + key.title() + ' synonyms are:') for value in values: print('\t- ' + value) else: print('\nI hope you enjoyed the program. Thank you.')
num = int(input("enter mobile no")) #6612312645 max=0 for i in range(1,11): a=num%10 num=num//10 if max<a: max=a print("max digit is "+str(max))
try: a=int(input("enter first number")) b=int(input("enter second number")) c=a/b print(c) except ZeroDivisionError: print("Denominator can not be zero") except ValueError: print("Enter Only Numeric Value") else: print("No Error Found") finally: print("Division Program")
f = int(input("enter the temprature in farenhite to convert on celsious")) #120 c = (5*f-160)/9 #print(c) print("Temprature in celsious is ",c)
class A: def fun1(self): print("A") class B: #B inherited by A class def fun2(self): print("B") class C(A,B): #C Multiple def fun3(self): print("C") class D(C): def fun4(self): print("D") obj = B() #obj.fun1() obj.fun2() obj1 = C() obj1.fun1() obj1.fun2() obj1.fun3() obj2 = D() obj2.fun1() obj2.fun2() obj2.fun3() obj2.fun4()
num = int(input("Enter Number To Check Prime")) i=1 c=0 while i<=num: if num%i==0: c=c+1 break i=i+1 if c==0: print("prime") else: print("not prime")
num = int(input("enter number")) #78923 a = num%10 #5 num=num//10 #1234 b = num%10 #4 num=num//10 #123 c = num%10 #3 num=num//10 #12 d = num%10 #2 e= num//10 #1 num1 = e*10000+b*1000+c*100+d*10+a*1 print(num1)
num= int(input("enter number")) i=num f=1 s="" while(i>=1): f=f*i if i>1: s=s+ str(i) +"*" else: s=s+str(i) i=i-1 print(s+"="+str(f))
# Assessment 2 @ Noroff University College _author_ = "Thomas Thaulow" copyright = "Thomas Thaulow" _email_ = "thaulow@thaulow.co" import random ###################################### #======== 6x6 Sudoku Boards =========# ###################################### board1 = [[0, 6, 0, 0, 0, 0], # Row 0 [0, 0, 0, 6, 2, 4], # Row 1 [3, 0, 4, 0, 1, 0], # Row 2 [0, 0, 0, 2, 0, 0], # Row 3 [0, 0, 0, 4, 5, 0], # Row 4 [0, 0, 1, 0, 0, 2]] # Row 5 board2 = [[6, 4, 0, 1, 2, 0], # Row 0 [1, 0, 2, 0, 0, 4], # Row 1 [5, 0, 4, 2, 3, 6], # Row 2 [2, 0, 0, 0, 0, 0], # Row 3 [4, 5, 0, 3, 0, 0], # Row 4 [0, 0, 1, 0, 6, 0]] # Row 5 board3 = [[0, 6, 0, 3, 5, 0], # Row 0 [3, 4, 5, 0, 0, 0], # Row 1 [5, 1, 6, 3, 0, 3], # Row 2 [0, 0, 0, 5, 1, 0], # Row 3 [4, 0, 1, 6, 0, 5], # Row 4 [6, 0, 3, 4, 2, 1]] # Row 5 boards = [board1, board2, board3] # Function for selecting a random board def get_board(): length = len(boards) random_board_number = random.randrange(length) board = boards[random_board_number] return board # Function for getting Assignment 2 board def get_noroff_board(): board = board1 return board
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from flask import request, redirect, flash from system.core.controller import * class Courses(Controller): def __init__(self, action): super(Courses, self).__init__(action) self.load_model('Course') """ This is an example of loading a model. Every controller has access to the load_model method. self.load_model('WelcomeModel') """ """ This is an example of a controller method that will load a view for the client """ def index(self): all_courses = self.models['Course'].get_all_courses() return self.load_view('index.html', courses=all_courses) def create(self): course_details = { 'name': request.form['name'], 'description': request.form['description'] } self.models['Course'].add_course(course_details) return redirect('/') def show_confirm(self, id): one_course = self.models['Course'].get_course_by_id(id) return self.load_view('show.html', course=one_course[0]) def destroy(self, id): self.models['Course'].destroy(id) return redirect('/')
# Square wheel import turtle jack = turtle.Turtle() jack.color("green") jack.speed(0) def draw_square(distanse): for side in range(4): jack.forward(distanse) jack.right(90) for square in range(72): draw_square(150) jack.forward(5) jack.left(5) jack.hideturtle() turtle.done()
import random '''Class containing all the process for the processing of the music; transform the concept of the emotion into musical parts''' class Music: '''Match the musical modes with diffent modes and storages the notes in them emotion_to_modes: this variable matchs every emotion with differnet modes and their musical notes modes_to_notes: this variable contains the modes and their musical notes modes_to_chords: this variable prepare some chords to set the base of the progression of the musical composition ''' def __init__(self): self.emotion_to_modes = { "happy": {"ionian": ["C", "D", "E", "F", "G", "A", "B"], "dorian": ["C", "D", "Eb", "F", "G", "A", "Bb"], "lydian": ["C", "D", "E", "F#", "G", "A", "B"], "mixolydian": ["C", "D", "E", "F", "G", "A", "Bb"]}, "sad": {"aeolian": ["C", "D", "Eb", "F", "G", "Ab", "Bb"]}, "scared": {"locrian": ["C", "Db", "Eb", "F", "Gb", "Ab", "Bb"]}, "angry": {"phrygian": ["C", "Db", "Eb", "F", "G", "Ab", "Bb"], "mixolydian": ["C", "D", "E", "F", "G", "A", "Bb"]}, "neutral": {"dorian": ["C", "D", "Eb", "F", "G", "A", "Bb"]}, "surprised": {"ionian": ["C", "D", "E", "F", "G", "A", "B"], "lydian": ["C", "D", "E", "F#", "G", "A", "B"]}, "disgusted": {"locrian": ["C", "Db", "Eb", "F", "Gb", "Ab", "Bb"]} } self.modes_to_notes = { "ionian": ["C", "D", "E", "F", "G", "A", "B"], "aeolian": ["C", "D", "Eb", "F", "G", "Ab", "Bb"], "dorian": ["C", "D", "Eb", "F", "G", "A", "Bb"], "phrygian": ["C", "Db", "Eb", "F", "G", "Ab", "Bb"], "lydian": ["C", "D", "E", "F#", "G", "A", "B"], "mixolydian": ["C", "D", "E", "F", "G", "A", "Bb"], "locrian": ["C", "Db", "Eb", "F", "Gb", "Ab", "Bb"] } #chods progressions self.modes_to_chords = { "ionian": {"a": ["C", "Dm", "Em", "F", "G", "Am", "Bdim"]}, "aeolian": {"a": ["Cm", "Fm", "Gm", "Cm"], "b": ["Cm", "Bb", "Ab", "Gm", "Cm"], "c": ["Cm", "Bb", "Ab", "Bb", "Eb", "Gm", "Cm"], "d": ["Cm", "Ab", "Eb", "Fm", "Cm"]}, "dorian": {"a": ["Cm", "F", "Cm", "Bb", "Cm", "Gm", "Cm"], "b": ["Cm", "Bb", "F", "Gm", "Cm"], "c": ["Cm", "Gm", "Cm", "F", "Bb", "Eb", "Bb", "Cm"]}, "phrygian": {"a": ["Cm", "Db", "Cm", "Ab", "Cm", "Eb", "Fm", "Cm"]}, "lydian": {"a": ["C", "D", "G", "C", "Am", "D", "G", "C"], "b": ["C", "D", "Em", "Bm", "C", "D", "C"]}, "mixolydian": {"a": ["C", "F", "Gm", "C"], "b": ["C", "F", "Dm", "Gm", "Am", "Gm", "C"], "c": ["C", "Bb", "C", "F", "Gm", "Bb", "C"], "d": ["C", "Bb", "C", "F", "Gm", "Bb", "C"]}, "locrian": {"a": ["Bdim", "C", "Dm", "Em", "F", "G", "Am"]} } def get_modes_to_chords(self): return self.modes_to_chords def get_modes_to_notes(self): return self.modes_to_notes def get_modes(self): return self.emotion_to_modes def get_notes_from_emotion(self, emotion): if emotion in self.emotion_to_modes: return self.emotion_to_modes[emotion] def get_first_mode(self, mode_dict): '''returns first key of the dictionary''' return list(mode_dict.keys())[0] def list_of_notes(self,emotion): if emotion in self.emotion_to_modes: notes = self.emotion_to_modes[emotion] notes = self.get_first_mode(notes) notes = self.modes_to_notes[notes] list_notes = [self.match_notes_to_midi_numbers()[number_notes] for number_notes in notes] return self.get_middle_val_list(list_notes) def get_middle_val_list(self,list_notes): return [self.findMiddle(notes) for notes in list_notes] def findMiddle(self, input_list): middle = float(len(input_list))/2 if middle % 2 != 0: return input_list[int(middle - .5)] else: return (input_list[int(middle)], input_list[int(middle-1)]) def match_notes_to_midi_numbers(self): return { 'C' : [0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120], 'C#' : [1, 13, 25, 37, 49, 61, 73, 85, 97, 109, 121], 'Db' : [1, 13, 25, 37, 49, 61, 73, 85, 97, 109, 121], 'D' : [2, 14, 26, 38, 50, 62, 74, 86, 98, 110, 122], 'D#' : [3, 15, 27, 39, 51, 63, 75, 87, 99, 111, 123], 'Eb' : [3, 15, 27, 39, 51, 63, 75, 87, 99, 111, 123], 'E' : [4, 16, 28, 40, 52, 64, 76, 88, 100, 112, 124], 'F' : [5, 17, 29, 41, 53, 65, 77, 89, 101, 113, 125], 'F#' : [6, 18, 30, 42, 54, 66, 78, 90, 102, 114, 126], 'Gb' : [6, 18, 30, 42, 54, 66, 78, 90, 102, 114, 126], 'G' : [7, 19, 31, 43, 55, 67, 79, 91, 103, 115, 127], 'G#' : [8, 20, 32, 44, 56, 68, 80, 92, 104, 116], 'Ab' : [8, 20, 32, 44, 56, 68, 80, 92, 104, 116], 'A' : [9, 21, 33, 45, 57, 69, 81, 93, 105, 117], 'A#' : [10, 22, 34, 46, 58, 70, 82, 94, 106, 118], 'Bb' : [10, 22, 34, 46, 58, 70, 82, 94, 106, 118], 'B' : [11, 23, 35, 47, 59, 71, 83, 95, 107, 119] } if __name__ == '__main__': test = Music() print (test.list_of_notes('angry'))
""" Newton-Raphson for square root Fix x such that x**2 - 24 is within epsilon of 0 Add some code to the implementation of Newton-Raphson that keeps track of the number of iterations used to find the root. Use that code as part of a program that compares the efficiency of Newton-Raphson and bisection search. (You should discover that Newton-Raphson is more efficient.) """ epsilon = 0.01 k = 24.0 guess = k/2.0 while abs(guess*guess - k) >= epsilon: guess = guess - (((guess**2) - k) / (2*guess)) print('square root of', k, 'is about', guess)
def add(x, y): return x * y def main(): print(add(5, 2)) # 10 if __name__ == '__main__': exit(main())
#libraries from datetime import date import datetime #global constans viriable userList = []#This initialise userlist to nothing. passList = []#this initialise passlist to nothing #define function def reg_user(): newusername = input("Enter New username: ")#This will input the username when user want to log in,it will request a username. while True:#This uses while loop because we want the loop to continue looping if the condition is True. if not newusername in userList:#This uses if statement to check the condition of username in userlist. break#This also break the loop for infiniting else: print("username already exits,try different username!") #This if the condition is false,it will print wrong username newusername = input("Enter New username: ")#This ask the user to re-enter the username if it is invalid. user_password = input("Please enter new password: ") confirmation = input("Please confirm the password: ") if user_password == confirmation:#This compares the user_password to confirmation. userfile = open("user.txt","a")#This open the file in append mode userfile.write("\n" + newusername + ', '+ user_password)#This will input username and password in a newline userfile.close() checker = 1 else: print('password do not match') def add_task(): # # if choice == "a":#If the user selected a,the input should ask the user to input the new username,title,task description,date assigned,due dateand completion of the task. new_username = input("Who task assigned to:")#This will ask the user,who the task assigned to. title = input("Please enter the title of the task:")#This will ask the title of the task. task_description = input("What is the task description? ")#This will ask the discription of the task. date_assigned = date.today()#This will ask the date,the task assigned. due_date = input("Please enter the due date of the task:")#This will ask the due date of the task. completion = "No"#This ask the tasks are complete or not,so here since we adding task,we keep adding them,when neceessary to add,there no completion. userfile = open("tasks.txt","a")#This will append the task.txt. userfile.write("\n" + new_username + ', '+ title + ', ' + task_description + ', '+ str(date_assigned) + ', ' + due_date + ', ' + completion)#this will continue write tasks in a format way. userfile.close()#After writting or reading we close the task. return_to_the_main = input('Do you want to return to the main manu?:press -1') def view_all(): # if choice == "va":#IF the choice is va,it will need the user to open reading mode of the file. with open("tasks.txt","r") as userfile:#THis the reading mode of the text file,and it automatically close after reading or writting. for line in userfile:#This will loop the userfile,because we want it to read each and line of the file taskslist = line.split(', ')#this split the tasks separated by comma and a space. print('Task:\t'+taskslist[1])#Task in tasklist is in index[1]. print('Assing to:\t'+taskslist[0])#assign to in tasklist is in index[0] print('Date assigned:\t'+taskslist[3])#Date assigned in tasklist is in index [3] print('Due date:\t'+taskslist[4])#Due date in tasklist is in index[4] print('Task complete?\t'+taskslist[5])#Task complete in tasklist is in index[5] print('Task description:\t'+taskslist[2])#Task description in tasklist is in index[2] def view_mine(): #This define the function view mine(). j =0 #This i =[] tasks = {} with open('tasks.txt','r') as myfile: lines = myfile.readlines() for num,line in enumerate(lines): taskslist = line.split(', ')#this split the tasks separated by comma and a space. tasks[num] = taskslist if username == taskslist[0]:#This compares username to tasklist[0] print(f"The task number is: {num}") print('Task:\t'+taskslist[1])#Task in tasklist is in index[1]. print('Assign to:\t'+taskslist[0])#assign to in tasklist is in index[0] print('Date assigned:\t'+taskslist[3])#Date assigned in tasklist is in index [3] print('Due date:\t'+taskslist[4])#Due date in tasklist is in index[4] print('Task complete?\t'+taskslist[5])#Task complete in tasklist is in index[5] print('Task description:\t'+taskslist[2])#Task description in tasklist is in index[2] task_num = int(input("Please select the input you would like to edit: ")) task = tasks[task_num] edit_option = input('''Would you like to: e-edit task c- mark complete -1 - return to main menu\n''') if edit_option == 'e': edit_option2 = input('''Would you like to: d - change due date u - change user name \n''') if edit_option2 == 'd': new_due_date = input("Enter new_due_date: ") task[-2] = new_due_date if edit_option2 == "u": task['assigned_to'] = input("Please enter new user: ") nu_tasks = [task[tasks]for task in tasks] with open('tasks.txt','r') as userFile: num_task = 0 # if userFile == taskslist[0]:#This compares username to tasklist[0] # print('Task Number: ' + int(num_task) + '\nUsername: ' + taskslist[0] + '\nTitle: ' + taskslist[1] + '\nTask Discription:' + taskslist[2] + '\nDue Date: ' + taskslist[3] + '\nCompleted ' + taskslist[4] + '\n') #edit_Task = input('Would you like to edit a task? edit or return to the manu?(-1)') elif edit_option == 'c': task[5] = input("Mark complete? Yes or No? ") if task[0] == "No": edit_Task = input('Would you like to edit a task? edit, Yes or No? or return to the manu?(-1)') def generate_taskOverview(): taskfile = open('tasks.txt','r') tasklist = taskfile.readlines() taskfile.close() total_numb_task = len(tasklist) numb_of_incompleted_tasks = 0 numb_of_completed_tasks = 0 overdue_tasks = 0 for task in tasklist: compl = task.strip('\n').split(', ')[-1] print(compl) if compl.lower() == 'yes': numb_of_completed_tasks += 1 else: numb_of_incompleted_tasks += 1 strdate = task.strip('\n').split(', ')[-2] dObject = datetime.datetime.strptime(strdate, '%d %b %Y') currentdate = datetime.datetime.now() if dObject < currentdate: overdue_tasks +=1 percentage_incompleted = (numb_of_incompleted_tasks/total_numb_task) * 100 percentage_completed = (numb_of_completed_tasks/total_numb_task) * 100 percentage_overdue = (overdue_tasks/total_numb_task)*100 task_overview_file = open('task_overview.txt', 'w') task_overview_file.write(f'The total number of task is {total_numb_task}\n' ) task_overview_file.write(f'The total number of completed tasks generated by taskmanager.py is {numb_of_completed_tasks}\n') task_overview_file.write(f'The total number of incompleted tasks generated by taskmanager.py is {numb_of_incompleted_tasks}\n ') task_overview_file.write(f'The total percentage of completed tasks generated by taskmanager.py is {percentage_completed}%\n ') task_overview_file.write(f'The total percentage of incompleted tasks generated by taskmanager.py is {percentage_incompleted}%\n ') print(f'The total number of incompleted tasks that are overdue generated by taskmanager.py is {overdue_tasks} \n') print(f'The total percentage of incompleted tasks that are overdue generated by taskmanager.py is {percentage_overdue}%\n') def for_each_user(tn, user_n = 'admin'): taskfile = open('tasks.txt','r') tasklist = taskfile.readlines() taskfile.close() total_numb_task = 0 #This initialises the total number of task numb_of_completed_tasks = 0 #This Initialises the completed task numb_0f_incompleted_tasks = 0 #This initialises the incompleted task task_count = 0 #This Initialises the number of task. currentdate = datetime.datetime.now() #This initialises the date and time. for t in tasklist: #This will loop through the tasklist and tis a temporal variable. task_count += 1 #This increment the number of task user = t.split(', ')[0] #This will split the user with comma and space. compl = t.strip('\n').split(', ')[-1] if user == user_n: #This compare the user with user_n total_numb_task += 1 #This increment the number of task if compl.lower() == 'yes': #This compares the completed task with yes numb_of_completed_tasks += 1 #This increment the numb_of_completed task. else: #This shows if the task are incomplete,its a no numb_0f_incompleted_tasks +=1 #This will increment the number task that are not complete. percentage_of_task = (total_numb_task/task_count)*100 #This calculate the percentage of task percentage_completed = (numb_of_completed_tasks/total_numb_task) * 100 #This calculate the percentage of completed task percentage_incompleted = (numb_0f_incompleted_tasks/total_numb_task) * 100 #This calculate the percentage of incompleted task. user_overview_file = open('user_overview.txt','w') #This open the file user_overview on writting mode. user_overview_file.write(f'Details for user {user_n}\n______') #This will desplay the user. user_overview_file.write(f'The total number of task are {total_numb_task}\n') #This will dessplay the number of task that are assigned to the user. user_overview_file.write (f'The percentage of task assigned to user are {percentage_of_task} %\n') #This will desplay the percentage of task that assigned to the user. user_overview_file.write(f'The total percentage of completed tasks by user is {percentage_completed}%\n ') #This will display the total percentage of task that are completed by a user. user_overview_file.write(f'The total percentage of tasks that are not yet completed and overdue by user is {percentage_incompleted}%\n ') #This will display the task that are incomplete def user_overview(): #This define the function. taskfile = open('tasks.txt','r') #This open the file tasks.txt in a reading mode tasklist = taskfile.readlines() #This read the file each and every line. taskfile.close() #This close the file. total_numb_tasks = len( tasklist) #This measure the length of the tasklist. userfile = open('user.txt','r') #This open the user.txt in a reading mode. userlist = userfile.readlines() #This read the file(userlist) each and every line. userfile.close() #This closes the file(userfile) total_numb_users = len( userlist) print(f'The total number of users is {total_numb_users}\n' ) #This will print the total nuber of users. print(f'The total number of task is {total_numb_tasks}\n' ) #This will print the total number of task for_each_user(tn=total_numb_tasks) def generate_reports(): #This is defining the function. generate_taskOverview() #This is defining the function user_overview() #This is calling def display_statistics(): #This define the function of the stats generate_taskOverview() user_overview() print("Displaying statistics for admin:\n") #This will print(Display statistics for admin:) and jump to new line. with open('task_overview.txt','r') as f: #This will open the file (task_overview.txt) in a reading mode. fil = f.read() #This read each and every line in a file print(fil) #this will print the information inside the file(fil) with open("user_overview.txt",'r') as time: #This will open the file in a reading mode tell = time.read() #This will read the lines of the file print(tell) #This will print the information inside(tell) #main function userFile = open("user.txt", "r")#This read the file in userfile. for line in userFile:#This loop the userfile usern, passw = line.strip("\n").split(", ") #This strip the characters in usern and passw which are initialised by line,after after striping the empty spaces from left to right in to new line,it split usern with a comma and space to passw. userList.append(usern)#This will append the usern. passList.append(passw)#This will also append the passw username = input("Enter username: ")#This will input the username when user want to log in,it will request a username. while True:#This uses while loop because we want the loop to continue looping if the condition is True. if username in userList:#This uses if statement to check the condition of username in userlist. for index, user in enumerate(userList):#This uses for loop to numerate index and user in userlist. if user == username:#This compare user to username passwordIndex = index break#The loop is True,it does not stop until you break it. break#This also break the loop for infiniting else: print("wrong user name, try again.")#This if the condition is false,it will print wrong username username = input("Enter username: ")#This ask the user to re-enter the username if it is invalid. password = input("Enter the password: ")#This ask the user to input the password while True:#This also True,so the user uses while loop to make the loop run until it is True. if password == passList[passwordIndex]:#This initialises passwordIndex to password break#This stops the loop from running else: print("Invalid password,re-enter the password")#This print wrong password if the condition is falls password = input("Enter the password: ")#This Will ask the user to re enter the password until the condition is True. pass #while 1: if username == 'admin':#This compares admin to username choice=input('''Please select one of the following options: r - register user a - add task: va - veiw all tasks: vm - view my tasks: gr - generate reports: ds - display statistics: e - exit\n''')#This ask the user to input the option. else: choice=input('''Please select one of the following options: a - add task: va - veiw all tasks: vm - view my tasks: e - exit\n''') if choice == 'gr': #This if the user chose the option gr generate_reports() #This is calling the function if choice == 'ds': #This is the choice of the user display_statistics() #This is calling the function. if choice == "r":#This shows if the user chose the first option,the following will be asked as input reg_user() #This is calling the function if choice == 'a': add_task() #This is calling the function if choice == "va":#IF the choice is va,it will need the user to open reading mode of the file view_all() if choice == "vm":#if the choice is vm,the user will open the file in a reading mode view_mine() #This is calling the function # print('Assing to:\t'+taskslist[0])#assign to in tasklist is in index[0] # print('Date assigned:\t'+taskslist[3])#Date assigned in tasklist is in index [3] # print('Due date:\t'+taskslist[4])#Due date in tasklist is in index[4] # print('Task complete?\t'+taskslist[5])#Task complete in tasklist is in index[5] # print('Task description:\t'+taskslist[2])#Task description in tasklist is in index[2]
''' This is a python script to read CDF V3 files without needing to install the CDF NASA library. You will need Python version 3, as well as the Numpy library to use this module. To install, open up your terminal/command prompt, and type:: pip install cdflib ########## CDF Class ########## To begin accessing the data within a CDF file, first create a new CDF class. This can be done with the following commands:: import cdflib cdf_file = cdflib.CDF('/path/to/cdf_file.cdf') Then, you can call various functions on the variable. For example:: x = cdf_file.varget("NameOfVariable", startrec = 0, endrec = 150) This command will return all data inside of the variable "Variable1", from records 0 to 150. Below is a list of the 8 different functions you can call. cdf_info() ============= Returns a dictionary that shows the basic CDF information. This information includes +---------------+--------------------------------------------------------------------------------+ | ['CDF'] | the name of the CDF | +---------------+--------------------------------------------------------------------------------+ | ['Version'] | the version of the CDF | +---------------+--------------------------------------------------------------------------------+ | ['Encoding'] | the endianness of the CDF | +---------------+--------------------------------------------------------------------------------+ | ['Majority'] | the row/column majority | +---------------+--------------------------------------------------------------------------------+ | ['zVariables']| the dictionary for zVariable numbers and their corresponding names | +---------------+--------------------------------------------------------------------------------+ | ['rVariables']| the dictionary for rVariable numbers and their corresponding names | +---------------+--------------------------------------------------------------------------------+ | ['Attributes']| the dictionary for attribute numbers and their corresponding names and scopes | +---------------+--------------------------------------------------------------------------------+ varinq(variable) ============= Returns a dictionary that shows the basic variable information. This information includes +-----------------+--------------------------------------------------------------------------------+ | ['Variable'] | the name of the variable | +-----------------+--------------------------------------------------------------------------------+ | ['Num'] | the variable number | +-----------------+--------------------------------------------------------------------------------+ | ['Var_Type'] | the variable type: zVariable or rVariable | +-----------------+--------------------------------------------------------------------------------+ | ['Data_Type'] | the variable's CDF data type | +-----------------+--------------------------------------------------------------------------------+ | ['Num_Elements']| the number of elements of the variable | +-----------------+--------------------------------------------------------------------------------+ | ['Num_Dims'] | the dimensionality of the variable record | +-----------------+--------------------------------------------------------------------------------+ | ['Dim_Sizes'] | the shape of the variable record | +-----------------+--------------------------------------------------------------------------------+ | ['Sparse'] | the variable's record sparseness | +-----------------+--------------------------------------------------------------------------------+ | ['Last_Rec'] | the maximum written record number (0-based) | +-----------------+--------------------------------------------------------------------------------+ attinq( attribute = None) ============= Returns a python dictionary of attribute information. If no attribute is provided, a list of all attributes is printed. attget( attribute = None, entry = None ) ============= Returns the value of the attribute at the entry number provided. A variable name can be used instead of its corresponding entry number. A dictionary is returned with the following defined keys +-----------------+--------------------------------------------------------------------------------+ | ['Item_Size'] | the number of bytes for each entry value | +-----------------+--------------------------------------------------------------------------------+ | ['Num_Items'] | total number of values extracted | +-----------------+--------------------------------------------------------------------------------+ | ['Data_Type'] | the CDF data type | +-----------------+--------------------------------------------------------------------------------+ | ['Data'] | retrieved attribute data as a scalar value, a numpy array or a string | +-----------------+--------------------------------------------------------------------------------+ varattsget(variable = None) ============= Gets all variable attributes. Unlike attget, which returns a single attribute entry value, this function returns all of the variable attribute entries, in a dictionary (in the form of 'attribute': value pair) for a variable. If there is no entry found, None is returned. If no variable name is provided, a list of variables are printed. globalattsget() ============= Gets all global attributes. This function returns all of the global attribute entries, in a dictionary (in the form of 'attribute': {entry: value} pair) from a CDF. If there is no entry found, None is returned. varget( variable = None, [epoch=None], [[starttime=None, endtime=None] | [startrec=0, endrec = None]], [,expand=True]) ============= Returns the variable data. Variable can be entered either a name or a variable number. By default, it returns a 'numpy.ndarray' or 'list' class object, depending on the data type, with the variable data and its specification. If "expand" is set as True, a dictionary is returned with the following defined keys for the output +-----------------+--------------------------------------------------------------------------------+ | ['Rec_Ndim'] | the dimension number of each variable record | +-----------------+--------------------------------------------------------------------------------+ | ['Rec_Shape'] | the shape of the variable record dimensions | +-----------------+--------------------------------------------------------------------------------+ | ['Num_Records'] | the number of the retrieved records | +-----------------+--------------------------------------------------------------------------------+ | ['Data_Type'] | the CDF data type | +-----------------+--------------------------------------------------------------------------------+ | ['Data'] | retrieved variable data | +-----------------+--------------------------------------------------------------------------------+ By default, the full variable data is returned. To acquire only a portion of the data for a record-varying variable, either the time or record (0-based) range can be specified. 'epoch' can be used to specify which time variable this variable depends on and is to be searched for the time range. For the ISTP-compliant CDFs, the time variable will come from the attribute 'DEPEND_0' from this variable. The function will automatically search for it thus no need to specify 'epoch'. If either the start or end time is not specified, the possible minimum or maximum value for the specific epoch data type is assumed. If either the start or end record is not specified, the range starts at 0 or/and ends at the last of the written data. Note: CDF's CDF_EPOCH16 data type uses 2 8-byte doubles for each data value. In Python, each value is presented as a complex or numpy.complex128. epochrange( epoch, [starttime=None, endtime=None]) ============= Get epoch range. Returns a list of the record numbers, representing the corresponding starting and ending records within the time range from the epoch data. A None is returned if there is no data either written or found in the time range. Sample use - import cdflib swea_cdf_file = cdflib.CDF('/path/to/swea_file.cdf') swea_cdf_file.cdf_info() x = swea_cdf_file.varget('NameOfVariable') swea_cdf_file.close() @author: Bryan Harter, Michael Liu ''' import os import numpy as np import sys import gzip import hashlib import cdflib class CDF(object): def __init__(self, path, validate=None): #READ FIRST INTERNAL RECORDS try: f = open(path, 'rb') except: try: f = open(path+'.cdf', 'rb') except: print('CDF:',path,' not found') return self.file = f self.file.seek(0) magic_number = f.read(4).hex() if magic_number != 'cdf30001': print('Not a CDF V3 file or a non-supported CDF!') return compressed_bool = f.read(4).hex() self._compressed = not (compressed_bool == '0000ffff') self._reading_compressed_file = False if self._compressed: new_path = self._uncompress_file(path) if new_path == None: print("Decompression was unsuccessful. Only GZIP compression is currently supported.") f.close() return self.file= open(new_path, 'rb') path = new_path self.file.seek(8) self._reading_compressed_file = True cdr_info = self._read_cdr(self.file.tell()) gdr_info = self._read_gdr(self.file.tell()) if cdr_info['md5'] and (validate != None): if not self._md5_validation(gdr_info['eof']): print('This file fails the md5 checksum....') f.close() return if not cdr_info['format']: print('This package does not support multi-format CDF') f.close() return if cdr_info['encoding']==3 or cdr_info['encoding']==14 or cdr_info['encoding']==15: print('This package does not support CDFs with this '+ self._encoding_token(cdr_info['encoding'])+' encoding') f.close() return #SET GLOBAL VARIABLES self._path = path self._version = cdr_info['version'] self._encoding = cdr_info['encoding'] self._majority = self._major_token(cdr_info['majority']) self._copyright = cdr_info['copyright'] self._first_zvariable = gdr_info['first_zvariable'] self._first_rvariable = gdr_info['first_rvariable'] self._first_adr = gdr_info['first_adr'] self._num_zvariable = gdr_info['num_zvariables'] self._num_rvariable = gdr_info['num_rvariables'] self._rvariables_num_dims = gdr_info['rvariables_num_dims'] self._rvariables_dim_sizes = gdr_info['rvariables_dim_sizes'] self._num_att = gdr_info['num_attributes'] def __del__(self): self.close() def close(self): self.file.close() if self._reading_compressed_file: os.remove(self._path) self._reading_compressed_file = False def cdf_info(self): mycdf_info = {} mycdf_info['CDF'] = self._path mycdf_info['Version'] = self._version mycdf_info['Encoding'] = self._encoding mycdf_info['Majority'] = self._majority mycdf_info['rVariables'], mycdf_info['zVariables'] = self._get_varnames() mycdf_info['Attributes'] = self._get_attnames() mycdf_info['Copyright'] = self._copyright return mycdf_info def varinq(self, variable): vdr_info = self.varget(variable=variable, inq=True) if vdr_info == None: print("Variable name not found.") return var = {} var['Variable'] = vdr_info['name'] var['Num'] = vdr_info['variable_number'] var['Var_Type'] = self._variable_token(vdr_info['section_type']) var['data_type'] = vdr_info['data_type'] var['data_type_description'] = self._datatype_token(vdr_info['data_type']) var['Num_Elements'] = vdr_info['num_elements'] var['Num_Dims'] = vdr_info['num_dims'] var['Dim_Sizes'] = vdr_info['dim_sizes'] var['Sparse'] = self._sparse_token(vdr_info['sparse']) var['Last_Rec'] = vdr_info['max_records'] return var def attinq(self, attribute = None): position = self._first_adr if isinstance(attribute, str): for _ in range(0, self._num_att): name, next_adr = self._read_adr_fast(position) if name.strip().lower() == attribute.strip().lower(): return self._read_adr(position) position = next_adr print('No attribute by this name:',attribute) return elif isinstance(attribute, int): if (attribute < 0 or attribute > self._num_zvariable): print('No attribute by this number:',attribute) return for _ in range(0, attribute): name, next_adr = self._read_adr_fast(position) position = next_adr return self._read_adr(position) else: print('Please set attribute keyword equal to the name or ', 'number of an attribute') attrs = self._get_attnames() for x in range(0, self._num_att): name = list(attrs[x].keys())[0] print('NAME: ' + name + ' NUMBER: ' + str(x) + ' SCOPE: ' + attrs[x][name]) def attget(self, attribute = None, entry = None): #Starting position position = self._first_adr #Get Correct ADR adr_info = None if isinstance(attribute, str): for _ in range(0, self._num_att): name, next_adr = self._read_adr_fast(position) if (name.strip().lower() == attribute.strip().lower()): adr_info = self._read_adr(position) break else: position = next_adr if adr_info == None: print("Attribute not found.") return elif isinstance(attribute, int): if (attribute < 0) or (attribute > self._num_att): print('No attribute by this number:',attribute) return if not isinstance(entry, int): print('Entry has to be a number...') return for _ in range(0, attribute): name, next_adr = self._read_adr_fast(position) position = next_adr adr_info = self._read_adr(position) else: print('Please set attribute keyword equal to the name or ', 'number of an attribute') for x in range(0, self._num_att): name, next_adr = self._read_adr_fast(position) print('NAME:'+name+' NUMBER: '+str(x)) position=next_adr return #Find the correct entry from the "entry" variable if adr_info['scope'] == 1: if not isinstance(entry, int): print('Global entry should be an integer') return num_entry_string = 'num_gr_entry' first_entry_string = 'first_gr_entry' max_entry_string = 'max_gr_entry' entry_num = entry else: var_num = -1 zvar = False if isinstance(entry, str): # a zVariable? positionx = self._first_zvariable for x in range(0, self._num_zvariable): name, vdr_next = self._read_vdr_fast(positionx) if (name.strip().lower() == entry.strip().lower()): var_num = x zvar = True break positionx = vdr_next if var_num == -1: # a rVariable? positionx = self._first_rvariable for x in range(0, self._num_rvariable): name, vdr_next = self._read_vdr_fast(positionx) if (name.strip().lower() == entry.strip().lower()): var_num = x break positionx = vdr_next if var_num == -1: print('No variable by this name:',entry) return entry_num = var_num else: if (self._num_zvariable > 0 and self._num_rvariable > 0): print('This CDF has both r and z variables. Use variable name') return if self._num_zvariable > 0: zvar = True entry_num = entry if zvar: num_entry_string = 'num_z_entry' first_entry_string = 'first_z_entry' max_entry_string = 'max_z_entry' else: num_entry_string = 'num_gr_entry' first_entry_string = 'first_gr_entry' max_entry_string = 'max_gr_entry' if entry_num > adr_info[max_entry_string]: print('The entry does not exist') return return self._get_attdata(adr_info, entry_num, adr_info[num_entry_string], adr_info[first_entry_string]) def varget(self, variable = None, epoch = None, starttime = None, endtime = None, startrec = 0, endrec = None, record_range_only=False, inq=False, expand=False): if (isinstance(variable, int) and self._num_zvariable > 0 and self._num_rvariable > 0): print('This CDF has both r and z variables. Use variable name') return if ((starttime != None or endtime != None) and (startrec != 0 or endrec != None)): print('Can\'t specify both time and record range') return if isinstance(variable, str): #Check z variables for the name, then r variables position = self._first_rvariable num_variables = self._num_rvariable vdr_info = None for _ in [0,1]: for _ in range(0, num_variables): name, vdr_next = self._read_vdr_fast(position) if name.strip().lower() == variable.strip().lower(): vdr_info = self._read_vdr(position) break position = vdr_next position = self._first_zvariable num_variables = self._num_zvariable if vdr_info == None: print("Variable name not found.") return elif isinstance(variable, int): if self._num_zvariable > 0: position = self._first_zvariable num_variable = self._num_zvariable elif self._num_rvariable > 0: position = self._first_rvariable num_variable = self._num_rvariable if (variable < 0 or variable >= num_variable): print('No variable by this number:',variable) return for _ in range(0, variable): name, next_vdr = self._read_vdr_fast(position) position = next_vdr vdr_info = self._read_vdr(position) else: print('Please set variable keyword equal to the name or ', 'number of an variable') rvars, zvars = self._get_varnames() print("RVARIABLES: ") for x in rvars: print("NAME: "+str(x)) print("ZVARIABLES: ") for x in zvars: print("NAME: "+str(x)) return if inq: return vdr_info else: if (vdr_info['max_records'] < 0): #print('No data is written for this variable') return return self._read_vardata(vdr_info, epoch=epoch, starttime=starttime, endtime=endtime, startrec=startrec, endrec=endrec, record_range_only=record_range_only, expand=expand) def epochrange(self, epoch = None, starttime = None, endtime = None): return self.varget(variable=epoch, starttime=starttime, endtime=endtime, record_range_only=True) def globalattsget(self): byte_loc = self._first_adr return_dict = {} for _ in range(0, self._num_att): adr_info = self._read_adr(byte_loc) if (adr_info['scope'] != 1): byte_loc = adr_info['next_adr_location'] continue entries = [] if (adr_info['num_gr_entry'] == 0): continue for _ in range(0, adr_info['num_gr_entry']): aedr_info = self._read_aedr(adr_info['first_gr_entry']) entries.append(aedr_info['entry']) byte_loc = aedr_info['next_aedr'] if (entries != []): return_dict[adr_info['name']] = entries byte_loc = adr_info['next_adr_location'] return return_dict def varattsget(self, variable = None): if (isinstance(variable, int) and self._num_zvariable > 0 and self._num_rvariable > 0): print('This CDF has both r and z variables. Use variable name') return None if isinstance(variable, str): position = self._first_rvariable num_variables = self._num_rvariable for zVar in [0,1]: for _ in range(0, num_variables): name, vdr_next = self._read_vdr_fast(position) if name.strip().lower() == variable.strip().lower(): vdr_info = self._read_vdr(position) return self._read_varatts(vdr_info['variable_number'], zVar) position = vdr_next position = self._first_zvariable num_variables = self._num_zvariable print('No variable by this name:',variable) return None elif isinstance(variable, int): if self._num_zvariable > 0: num_variable = self._num_zvariable zVar = True else: num_variable = self._num_rvariable zVar = False if (variable < 0 or variable >= num_variable): print('No variable by this number:',variable) return None return self._read_varatts(variable, zVar) else: print('Please set variable keyword equal to the name or ', 'number of an variable') rvars, zvars = self._get_varnames() print("RVARIABLES: ") for x in rvars: print("NAME: "+ str(x)) print("ZVARIABLES: ") for x in zvars: print("NAME: " + str(x)) return def _uncompress_file(self, path): f = self.file data_start, data_size, cType, _ = self._read_ccr(8) if cType != 5: return f.seek(data_start) decompressed_data = gzip.decompress(f.read(data_size)) self.close() directory, filename = os.path.split(path) new_filename = filename+".gunzip" new_path = os.path.join(directory, new_filename) with open(new_path, 'wb') as newfile: newfile.write(bytearray.fromhex('cdf30001')) newfile.write(bytearray.fromhex('0000ffff')) newfile.write(decompressed_data) return new_path def _read_ccr(self, byte_loc): f = self.file f.seek(byte_loc, 0) block_size = int.from_bytes(f.read(8),'big') _ = int.from_bytes(f.read(4),'big') #Section Type cproffset = int.from_bytes(f.read(8),'big') #GDR Location _ = int.from_bytes(f.read(8),'big') #Size of file uncompressed _ = int.from_bytes(f.read(4),'big') #Reserved data_start = self.file.tell() data_size = block_size - 32 cType, cParams = self._read_cpr(cproffset) return data_start, data_size, cType, cParams def _read_cpr(self,byte_loc): f = self.file f.seek(byte_loc, 0) _ = int.from_bytes(f.read(8),'big') #Block Size, doesn't matter currently _ = int.from_bytes(f.read(4),'big') #Section Type cType = int.from_bytes(f.read(4),'big') _ = int.from_bytes(f.read(4),'big') #Reserved _ = int.from_bytes(f.read(4),'big') #parameter count, must be 1 cParams = int.from_bytes(f.read(4),'big') return cType, cParams def _md5_validation(self, file_size): ''' Verifies the MD5 checksum. Only used in the __init__() function ''' md5 = hashlib.md5() block_size = 16384 remaining = file_size self.file.seek(0) while (remaining > block_size): data = self.file.read(block_size) remaining = remaining - block_size md5.update(data) if (remaining > 0): data = self.file.read(remaining) md5.update(data) existing_md5 = self.file.read(16).hex() return (md5.hexdigest() == existing_md5) def _encoding_token(self, encoding): encodings = { 1: 'NETWORK', 2: 'SUN', 3: 'VAX', 4: 'DECSTATION', 5: 'SGi', 6: 'IBMPC', 7: 'IBMRS', 9: 'PPC', 11: 'HP', 12: 'NeXT', 13: 'ALPHAOSF1', 14: 'ALPHAVMSd', 15: 'ALPHAVMSg', 16: 'ALPHAVMSi'} return encodings[encoding] def _major_token(self, major): majors = { 1: 'Row_major', 2: 'Column_major'} return majors[major] def _scope_token(self, scope): scopes = { 1: 'Global', 2: 'Variable'} return scopes[scope] def _variable_token(self, variable): variables = { 3: 'rVariable', 8: 'zVariable'} return variables[variable] def _datatype_token(self, datatype): datatypes = { 1: 'CDF_INT1', 2: 'CDF_INT2', 4: 'CDF_INT4', 8: 'CDF_INT8', 11: 'CDF_UINT1', 12: 'CDF_UINT2', 14: 'CDF_UINT4', 21: 'CDF_REAL4', 22: 'CDF_REAL8', 31: 'CDF_EPOCH', 32: 'CDF_EPOCH16', 33: 'CDF_TIME_TT2000', 41: 'CDF_BYTE', 44: 'CDF_FLOAT', 45: 'CDF_DOUBLE', 51: 'CDF_CHAR', 52: 'CDF_UCHAR' } return datatypes[datatype] def _sparse_token(self, sparse): sparses = { 0: 'No_sparse', 1: 'Pad_sparse', 2: 'Prev_sparse'} return sparses[sparse] def _get_varnames(self): zvars = [] rvars = [] if self._num_zvariable > 0: position = self._first_zvariable num_variable = self._num_zvariable for _ in range(0, num_variable): name, next_vdr = self._read_vdr_fast(position) zvars.append(name) position=next_vdr if self._num_rvariable > 0: position = self._first_rvariable num_variable = self._num_rvariable for _ in range(0, num_variable): name, next_vdr = self._read_vdr_fast(position) rvars.append(name) position=next_vdr return rvars, zvars def _get_attnames(self): attrs = [] attr = {} position = self._first_adr for _ in range(0, self._num_att): adr_info = self._read_adr(position) attr[adr_info['name']] = self._scope_token(int(adr_info['scope'])) attrs.append(attr) position=adr_info['next_adr_location'] return attrs def _read_cdr(self, byte_loc): f = self.file f.seek(byte_loc, 0) block_size = int.from_bytes(f.read(8),'big') _ = int.from_bytes(f.read(4),'big') #Section Type testing = int.from_bytes(f.read(8),'big') #GDR Location version=int.from_bytes(f.read(4),'big') release=int.from_bytes(f.read(4),'big') encoding = int.from_bytes(f.read(4),'big') #FLAG # #0 The majority of variable values within a variable record. Variable records are described in Chapter 4. Set indicates row-majority. Clear indicates column-majority. #1 The file format of the CDF. Set indicates single-file. Clear indicates multi-file. #2 The checksum of the CDF. Set indicates a checksum method is used. #3 The MD5 checksum method indicator. Set indicates MD5 method is used for the checksum. Bit 2 must be set. #4 Reserved for another checksum method. Bit 2 must be set and bit 3 must be clear .\ flag = int.from_bytes(f.read(4),'big') flag_bits = '{0:032b}'.format(flag) row_majority = (flag_bits[31]=='1') single_format = (flag_bits[30]=='1') md5 = (flag_bits[29]=='1' and flag_bits[28]=='1') _ = int.from_bytes(f.read(4),'big') #Nothing _ = int.from_bytes(f.read(4),'big') #Nothing increment = int.from_bytes(f.read(4),'big') _ = int.from_bytes(f.read(4),'big') #Nothing _ = int.from_bytes(f.read(4),'big') #Nothing length_of_copyright = (block_size-56) cdfcopyright = f.read(length_of_copyright).decode('utf-8') cdfcopyright = cdfcopyright.replace('\x00', '') cdr_info={} cdr_info['encoding'] = encoding cdr_info['copyright'] = cdfcopyright cdr_info['version'] = str(version) + '.' + str(release) + '.' + str(increment) if row_majority: cdr_info['majority'] = 1 else: cdr_info['majority'] = 2 cdr_info['format'] = single_format cdr_info['md5'] = md5 return cdr_info def _read_gdr(self, byte_loc): f = self.file f.seek(byte_loc, 0) _ = int.from_bytes(f.read(8),'big') #Block Size _ = int.from_bytes(f.read(4),'big') #Section Type first_rvariable = int.from_bytes(f.read(8),'big', signed=True) first_zvariable = int.from_bytes(f.read(8),'big', signed=True) first_adr = int.from_bytes(f.read(8),'big', signed=True) eof = int.from_bytes(f.read(8),'big', signed=True) num_rvariable = int.from_bytes(f.read(4),'big', signed=True) num_att = int.from_bytes(f.read(4),'big', signed=True) _ = int.from_bytes(f.read(4),'big', signed=True) #R Variable Max Record num_rdim = int.from_bytes(f.read(4),'big', signed=True) num_zvariable = int.from_bytes(f.read(4),'big', signed=True) _ = int.from_bytes(f.read(8),'big', signed=True) #Nothing _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing _ = int.from_bytes(f.read(4),'big', signed=True) #Leap Second Lat Update _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing #rDimSizes, depends on Number of dimensions for r variables #A bunch of 4 byte integers in a row. Length is (size of GDR) - 84 #In this case. there is nothing rdim_sizes=[] for _ in range(0, num_rdim): rdim_sizes.append(int.from_bytes(f.read(4),'big', signed=True)) gdr_info = {} gdr_info['first_zvariable'] = first_zvariable gdr_info['first_rvariable'] = first_rvariable gdr_info['first_adr'] = first_adr gdr_info['num_zvariables'] = num_zvariable gdr_info['num_rvariables'] = num_rvariable gdr_info['num_attributes'] = num_att gdr_info['rvariables_num_dims'] = num_rdim gdr_info['rvariables_dim_sizes'] = rdim_sizes gdr_info['eof'] = eof return gdr_info def _read_varatts(self, var_num, zVar): byte_loc = self._first_adr return_dict = {} for _ in range(0, self._num_att): adr_info = self._read_adr(byte_loc) if (adr_info['scope'] == 1): byte_loc = adr_info['next_adr_location'] continue if (zVar): byte_loc = adr_info['first_z_entry'] num_entry = adr_info['num_z_entry'] else: byte_loc = adr_info['first_gr_entry'] num_entry = adr_info['num_gr_entry'] for _ in range(0, num_entry): aedr_info = self._read_aedr(byte_loc) byte_loc = aedr_info['next_aedr'] if (aedr_info['entry_num'] != var_num): continue return_dict[adr_info['name']] = aedr_info['entry'] byte_loc = adr_info['next_adr_location'] return return_dict def _read_adr(self, byte_loc): f = self.file f.seek(byte_loc, 0) _ = int.from_bytes(f.read(8),'big') #Block Size _ = int.from_bytes(f.read(4),'big') #Section Type next_adr_loc = int.from_bytes(f.read(8),'big', signed=True) position_next_gr_entry = int.from_bytes(f.read(8),'big', signed=True) scope = int.from_bytes(f.read(4),'big', signed=True) num = int.from_bytes(f.read(4),'big', signed=True) num_gr_entry=int.from_bytes(f.read(4),'big', signed=True) MaxEntry=int.from_bytes(f.read(4),'big', signed=True) _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing position_next_z_entry =int.from_bytes(f.read(8),'big', signed=True) num_z_entry=int.from_bytes(f.read(4),'big', signed=True) MaxZEntry= int.from_bytes(f.read(4),'big', signed=True) _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing name = str(f.read(256).decode('utf-8')) name = name.replace('\x00', '') #Build the return dictionary return_dict = {} return_dict['scope'] = scope return_dict['next_adr_location'] = next_adr_loc return_dict['attribute_number'] = num return_dict['num_gr_entry'] = num_gr_entry return_dict['max_gr_entry'] = MaxEntry return_dict['num_z_entry'] = num_z_entry return_dict['max_z_entry'] = MaxZEntry return_dict['first_z_entry'] = position_next_z_entry return_dict['first_gr_entry'] = position_next_gr_entry return_dict['name'] = name return return_dict def _read_adr_fast(self, byte_loc): f = self.file #Position of next ADR f.seek(byte_loc+12, 0) next_adr_loc = int.from_bytes(f.read(8),'big', signed=True) #Name f.seek(byte_loc+68, 0) name = str(f.read(256).decode('utf-8')) name = name.replace('\x00', '') return name, next_adr_loc def _read_aedr_fast(self, byte_loc): f = self.file f.seek(byte_loc+12, 0) next_aedr = int.from_bytes(f.read(8),'big', signed=True) #Variable number or global entry number f.seek(byte_loc+28, 0) entry_num = int.from_bytes(f.read(4),'big', signed=True) return entry_num, next_aedr def _read_aedr(self, byte_loc): f = self.file f.seek(byte_loc, 0) block_size = int.from_bytes(f.read(8),'big') _ = int.from_bytes(f.read(4),'big') #Section Type next_aedr = int.from_bytes(f.read(8),'big', signed=True) _ = int.from_bytes(f.read(4),'big', signed=True) #Attribute number data_type = int.from_bytes(f.read(4),'big', signed=True) #Variable number or global entry number entry_num = int.from_bytes(f.read(4),'big', signed=True) #Number of elements #Length of string if string, otherwise its the number of numbers num_elements = int.from_bytes(f.read(4),'big', signed=True) #Supposed to be reserved space num_strings = int.from_bytes(f.read(4),'big', signed=True) if (num_strings < 1): num_strings = 1 #Literally nothing _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing #Always will have 56 bytes before the data byte_stream = f.read(block_size - 56) entry = self._read_data(byte_stream, data_type, 1, num_elements) return_dict = {} return_dict['entry'] = entry return_dict['data_type'] = data_type return_dict['num_elements'] = num_elements return_dict['num_strings'] = num_strings return_dict['next_aedr'] = next_aedr return_dict['entry_num'] = entry_num return return_dict def _read_vdr(self, byte_loc): f = self.file f.seek(byte_loc, 0) block_size = int.from_bytes(f.read(8),'big') #Type of internal record section_type = int.from_bytes(f.read(4),'big') next_vdr = int.from_bytes(f.read(8),'big', signed=True) data_type = int.from_bytes(f.read(4),'big', signed=True) max_rec = int.from_bytes(f.read(4),'big', signed=True) head_vxr = int.from_bytes(f.read(8),'big', signed=True) last_vxr = int.from_bytes(f.read(8),'big', signed=True) flags = int.from_bytes(f.read(4),'big', signed=True) flag_bits = '{0:032b}'.format(flags) record_variance_bool = (flag_bits[31]=='1') pad_bool = (flag_bits[30]=='1') compression_bool = (flag_bits[29]=='1') sparse = int.from_bytes(f.read(4),'big', signed=True) _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing _ = int.from_bytes(f.read(4),'big', signed=True) #Nothing num_elements = int.from_bytes(f.read(4),'big', signed=True) var_num = int.from_bytes(f.read(4),'big', signed=True) CPRorSPRoffset = int.from_bytes(f.read(8),'big', signed=True) blocking_factor = int.from_bytes(f.read(4),'big', signed=True) name = str(f.read(256).decode('utf-8')) name = name.replace('\x00', '') zdim_sizes = [] dim_sizes = [] dim_varys = [] if (section_type == 8): #zvariable num_dims = int.from_bytes(f.read(4),'big', signed=True) for _ in range(0, num_dims): zdim_sizes.append(int.from_bytes(f.read(4),'big', signed=True)) for _ in range(0, num_dims): dim_varys.append(int.from_bytes(f.read(4),'big', signed=True)) adj = 0 #Check for "False" dimensions, and delete them for x in range(0, num_dims): y = num_dims - x - 1 if (dim_varys[y]==0): del zdim_sizes[y] del dim_varys[y] adj = adj + 1 num_dims = num_dims - adj else: #rvariable for _ in range(0, self._rvariables_num_dims): dim_varys.append(int.from_bytes(f.read(4),'big', signed=True)) for x in range(0, self._rvariables_num_dims): if (dim_varys[x]!=0): dim_sizes.append(self._rvariables_dim_sizes[x]) num_dims = len(dim_sizes) #Only set if pad value is in the flags if (sparse == 1): if pad_bool: pad = f.read((block_size - (f.tell() - byte_loc))) else: pad = self._default_pad(data_type) return_dict = {} return_dict['data_type'] = data_type return_dict['section_type'] = section_type return_dict['next_vdr_location'] = next_vdr return_dict['variable_number'] = var_num return_dict['head_vxr'] = head_vxr return_dict['last_vxr'] = last_vxr return_dict['max_records'] = max_rec return_dict['name'] = name return_dict['num_dims'] = num_dims if (section_type == 8): return_dict['dim_sizes'] = zdim_sizes else: return_dict['dim_sizes'] = dim_sizes if (sparse == 1): return_dict['pad'] = pad return_dict['compression_bool'] = compression_bool return_dict['record_vary'] = record_variance_bool return_dict['num_elements'] = num_elements return_dict['sparse'] = sparse return return_dict def _read_vdr_fast(self, byte_loc): f = self.file f.seek(byte_loc+12, 0) next_vdr = int.from_bytes(f.read(8),'big', signed=True) f.seek(byte_loc+84, 0) name = str(f.read(256).decode('utf-8')) name = name.replace('\x00', '') return name, next_vdr def _read_vxrs(self, byte_loc, vvr_offsets=[], vvr_start=[], vvr_end=[]): f = self.file f.seek(byte_loc, 0) _ = int.from_bytes(f.read(8),'big', signed=True) # Block Size _ = int.from_bytes(f.read(4),'big') # Record Type next_vxr_pos = int.from_bytes(f.read(8),'big', signed=True) num_ent = int.from_bytes(f.read(4),'big', signed=True) num_ent_used = int.from_bytes(f.read(4),'big', signed=True) for ix in range(0, num_ent_used): f.seek(byte_loc+28+4*ix, 0) num_start = int.from_bytes(f.read(4),'big', signed=True) f.seek(byte_loc+28+(4*num_ent)+(4*ix), 0) num_end = int.from_bytes(f.read(4),'big', signed=True) f.seek(byte_loc+28+(8*num_ent)+(8*ix), 0) rec_offset = int.from_bytes(f.read(8),'big', signed=True) type_offset = 8 + rec_offset f.seek(type_offset, 0) next_type = int.from_bytes(f.read(4),'big', signed=True) if next_type == 6: vvr_offsets, vvr_start, vvr_end = self._read_vxrs(rec_offset, vvr_offsets=vvr_offsets, vvr_start=vvr_start, vvr_end=vvr_end) else: vvr_offsets.extend([rec_offset]) vvr_start.extend([num_start]) vvr_end.extend([num_end]) if next_vxr_pos != 0: vvr_offsets, vvr_start, vvr_end = self._read_vxrs(next_vxr_pos, vvr_offsets=vvr_offsets, vvr_start=vvr_start, vvr_end=vvr_end) return vvr_offsets, vvr_start, vvr_end def _read_vvrs(self, vdr_dict, vvr_offs, vvr_start, vvr_end): ''' Reads in all VVRS that are pointed to in the VVR_OFFS array. Creates a large byte array of all values called "byte_stream". Decodes the byte_stream, then returns them. ''' f = self.file numBytes = self._type_size(vdr_dict['data_type'], vdr_dict['num_elements']) numValues = self._num_values(vdr_dict) #Set size of byte_stream beforehand, otherwise its SUPER slow byte_stream = bytearray(numBytes*numValues*(vdr_dict['max_records']+1)) current_pos = 0 for vvr_num in range(0, len(vvr_offs)): f.seek(vvr_offs[vvr_num], 0) block_size = int.from_bytes(f.read(8),'big') section_type = int.from_bytes(f.read(4),'big') if section_type==7: data_size = block_size - 12 elif section_type==13: f.read(12) data_size = block_size - 24 if vvr_num ==0: if (vvr_start[vvr_num] != 0): fillRecs = vvr_start[vvr_num] for _ in range(0, fillRecs*numValues): uncompressed_bytes = bytearray(vdr_dict['pad']) byte_stream[current_pos:current_pos+len(uncompressed_bytes)] = uncompressed_bytes current_pos+=len(uncompressed_bytes) if section_type==13: uncompressed_bytes = gzip.decompress(f.read(data_size)) elif section_type==7: uncompressed_bytes = f.read(data_size) byte_stream[current_pos:current_pos+len(uncompressed_bytes)] = uncompressed_bytes current_pos+=len(uncompressed_bytes) pre_data = uncompressed_bytes[len(uncompressed_bytes)-numBytes*numValues:] else: fillRecs = vvr_start[vvr_num] - vvr_end[vvr_num -1] - 1 if (vdr_dict['sparse']==1): for _ in range(0, fillRecs*numValues): uncompressed_bytes = bytearray(vdr_dict['pad']) byte_stream[current_pos:current_pos+len(uncompressed_bytes)] = uncompressed_bytes current_pos+=len(uncompressed_bytes) elif (vdr_dict['sparse']==2): for _ in range(0, fillRecs): uncompressed_bytes = pre_data byte_stream[current_pos:current_pos+len(uncompressed_bytes)] = uncompressed_bytes current_pos+=len(uncompressed_bytes) if section_type==13: uncompressed_bytes = gzip.decompress(f.read(data_size)) elif section_type==7: uncompressed_bytes = f.read(data_size) byte_stream[current_pos:current_pos+len(uncompressed_bytes)] = uncompressed_bytes current_pos+=len(uncompressed_bytes) pre_data = uncompressed_bytes[len(uncompressed_bytes)-numBytes*numValues:] y = self._read_data(byte_stream, vdr_dict['data_type'], vdr_dict['max_records']+1, vdr_dict['num_elements'], dimensions=vdr_dict['dim_sizes']) return y def _convert_option(self): ''' Determines how to convert CDF byte ordering to the system byte ordering. ''' if sys.byteorder=='little' and self._endian() =='big-endian': #big->little order = '>' elif sys.byteorder=='big' and self._endian() =='little-endian': #little->big order = '<' else: #no conversion order = '=' return order def _endian(self): ''' Determines endianess of the CDF file Only used in __init__ ''' if (self._encoding==1 or self._encoding==2 or self._encoding==5 or self._encoding==7 or self._encoding==9 or self._encoding==11 or self._encoding==12): return 'big-endian' else: return 'little-endian' def _type_size(self, data_type, num_elms): ##DATA TYPES # #1 - 1 byte signed int #2 - 2 byte signed int #4 - 4 byte signed int #8 - 8 byte signed int #11 - 1 byte unsigned int #12 - 2 byte unsigned int #14 - 4 byte unsigned int #41 - same as 1 #21 - 4 byte float #22 - 8 byte float (double) #44 - same as 21 #45 - same as 22 #31 - double representing milliseconds #32 - 2 doubles representing milliseconds #33 - 8 byte signed integer representing nanoseconds from J2000 #51 - signed character #52 - unsigned character if (data_type == 1) or (data_type == 11) or (data_type == 41): return 1 elif (data_type == 2) or (data_type == 12): return 2 elif (data_type == 4) or (data_type == 14): return 4 elif (data_type == 8) or (data_type == 33): return 8 elif (data_type == 21) or (data_type == 44): return 4 elif (data_type == 22) or (data_type == 31) or (data_type == 45): return 8 elif (data_type == 32): return 16 elif (data_type == 51) or (data_type == 52): return num_elms def _read_data(self, byte_stream, data_type, num_recs, num_elems, dimensions=None): #NEED TO CONSTRUCT DATA TYPES FOR ARRAYS # #SOMETHING LIKE: # # dt = np.dtype('>(48,4,16)f4') squeeze_needed = False #If the dimension is [n], it needs to be [n,1] #for the numpy dtype. This requires us to squeeze #the matrix later, to get rid of this extra dimension. dt_string = self._convert_option() if dimensions!=None: if (len(dimensions) == 1): dimensions.append(1) squeeze_needed = True dt_string += '(' count = 0 for dim in dimensions: count += 1 dt_string += str(dim) if count < len(dimensions): dt_string += ',' dt_string += ')' if data_type==52 or data_type==51: #string if dimensions==None: ret = byte_stream[0:num_recs*num_elems].decode('utf-8') else: count = 1 for x in range (0, len(dimensions)): count = count * dimensions[x] strings = [] if (len(dimensions) == 0): strings = [byte_stream[i:i+num_elems].decode('utf-8') for i in range(0, num_recs*count*num_elems, num_elems)] else: for x in range (0, num_recs): onerec = [] onerec = [byte_stream[i:i+num_elems].decode('utf-8') for i in range(x*count*num_elems, (x+1)*count*num_elems, num_elems)] strings.append(onerec) ret = strings return ret else: if (data_type == 1) or (data_type == 41): dt_string += 'i1' elif data_type == 2: dt_string += 'i2' elif data_type == 4: dt_string += 'i4' elif (data_type == 8) or (data_type == 33): dt_string += 'i8' elif data_type == 11: dt_string += 'u1' elif data_type == 12: dt_string += 'u2' elif data_type == 14: dt_string += 'u4' elif (data_type == 21) or (data_type == 44): dt_string += 'f' elif (data_type == 22) or (data_type == 45) or (data_type == 31): dt_string += 'd' elif (data_type == 32): dt_string+= 'c' dt = np.dtype(dt_string) ret = np.frombuffer(byte_stream, dtype=dt, count=num_recs*num_elems) ret.setflags('WRITEABLE') if squeeze_needed: ret = np.squeeze(ret, axis=(ret.ndim-1)) #Put the data into system byte order if self._convert_option() != '=': ret = ret.byteswap().newbyteorder() return ret def _num_values(self, vdr_dict): ''' Returns the number of values from a given VDR dictionary Multiplies the dimension sizes of each dimension in the variable ''' values = 1 for x in range(0, vdr_dict['num_dims']): values = values * vdr_dict['dim_sizes'][x] return values def _get_attdata(self, adr_info, entry_num, num_entry, first_entry): position = first_entry for _ in range(0, num_entry): got_entry_num, next_aedr = self._read_aedr_fast(position) if entry_num == got_entry_num: aedr_info = self._read_aedr(position) return_dict = {} return_dict['Item_Size'] = self._type_size(aedr_info['data_type'], aedr_info['num_elements']) return_dict['Data_Type'] = self._datatype_token(aedr_info['data_type']) if (aedr_info['data_type'] == 51 or aedr_info['data_type'] == 52): return_dict['Num_Items'] = aedr_info['num_strings'] else: return_dict['Num_Items'] = aedr_info['num_elements'] if (aedr_info['data_type'] == 51 or aedr_info['data_type'] == 52) and (aedr_info['num_strings'] > 1): return_dict['Data'] = aedr_info['entry'].split('\\N ') elif (aedr_info['data_type'] == 32): return_dict['Data'] = complex(aedr_info['value'][0], aedr_info['value'][1]) else: return_dict['Data'] = aedr_info['entry'] return return_dict else: position = next_aedr print('The entry does not exist') return def _read_vardata(self, vdr_info, epoch=None, starttime=None, endtime=None, startrec=0, endrec=None, to_np=True, record_range_only = False, expand = False): #Error checking if startrec: if (startrec < 0): print('Invalid start recond') return None if endrec: if (endrec < 0) or (endrec > vdr_info['max_records']) or (endrec < startrec): print('Invalid end recond') return None else: endrec = vdr_info['max_records'] vvr_offsets, vvr_start, vvr_end = self._read_vxrs(vdr_info['head_vxr'], vvr_offsets=[], vvr_start=[], vvr_end=[]) data = self._read_vvrs(vdr_info, vvr_offsets, vvr_start, vvr_end) if (vdr_info['record_vary']): #Record varying if (starttime != None or endtime != None): recs = self._findtimerecords(vdr_info['name'], starttime, endtime, epoch = epoch) if (recs == None): return None if (isinstance(recs, tuple)): # back from np.where command for CDF_EPOCH and TT2000 idx = recs[0] if (len(idx) == 0): #no records in range return None else: startrec = idx[0] endrec = idx[len(idx)-1] else: startrec = recs[0] endrec = recs[1] else: startrec = 0 endrec = 0 if record_range_only: return [startrec, endrec] if (expand): new_dict = {} new_dict['Rec_Ndim'] = vdr_info['num_dims'] new_dict['Rec_Shape'] = vdr_info['dim_sizes'] new_dict['Num_Records'] = vdr_info['max_records'] + 1 new_dict['Item_Size'] = self._type_size(vdr_info['data_type'], vdr_info['num_elements']) new_dict['Data_Type'] = self._datatype_token(vdr_info['data_type']) if (vdr_info['record_vary']): if startrec==endrec: new_dict['Data'] = data[startrec] else: new_dict['Data'] = data[startrec:endrec+1] else: new_dict['Data'] = data[0] return new_dict else: if (vdr_info['record_vary']): if startrec==endrec: return data[startrec] else: return data[startrec:endrec+1] else: return data[0] def _findtimerecords(self, var_name, starttime, endtime, epoch=None): if (epoch != None): vdr_info = self.varinq(epoch) if (vdr_info == None): print('Epoch not found') return None if (vdr_info['data_type'] == 31 or vdr_info['data_type'] == 32 or vdr_info['data_type'] == 33): epochtimes = self.varget(epoch) else: vdr_info = self.varinq(var_name) if (vdr_info['data_type'] == 31 or vdr_info['data_type'] == 32 or vdr_info['data_type'] == 33): epochtimes = self.varget(var_name) else: #acquire depend_0 variable dependVar = self.attget('DEPEND_0', var_name) if (dependVar == None): print('No corresponding epoch from \'DEPEND_0\' attribute ', 'for variable:',var_name) print('Use \'epoch\' argument to specify its time-based variable') return None vdr_info = self.varinq(dependVar['Data']) if (vdr_info['data_type'] != 31 and vdr_info['data_type'] != 32 and vdr_info['data_type'] != 33): print('Corresponding variable from \'DEPEND_0\' attribute ', 'for variable:',var_name,' is not a CDF epoch type') return None epochtimes = self.varget(dependVar['Data']) return self._findrangerecords(vdr_info['data_type'], epochtimes, starttime, endtime) def _findrangerecords(self, data_type, epochtimes, starttime, endtime): if (data_type == 31 or data_type == 32 or data_type == 33): #CDF_EPOCH or CDF_EPOCH16 or CDF_TIME_TT2000 recs = cdflib.cdfepoch.findepochrange(epochtimes, starttime, endtime) else: print('Not a CDF epoch type...') return None return recs # #These functions below were developed by Michael Liu as a way to convert byte #streams to values without using numpy. Unfortunately, I could not get them to #work with variables that had multiple dimensions. # # import struct # # def _convert_type(self, data_type): # ''' # CDF data types to python struct data types # ''' # if (data_type == 1) or (data_type == 41): # dt_string = 'b' # elif data_type == 2: # dt_string = 'h' # elif data_type == 4: # dt_string = 'i' # elif (data_type == 8) or (data_type == 33): # dt_string = 'q' # elif data_type == 11: # dt_string = 'B' # elif data_type == 12: # dt_string = 'H' # elif data_type == 14: # dt_string = 'I' # elif (data_type == 21) or (data_type == 44): # dt_string = 'f' # elif (data_type == 22) or (data_type == 45) or (data_type == 31): # dt_string = 'd' # elif (data_type == 32): # dt_string = 'd' # elif (data_type == 51) or (data_type == 52): # dt_string = 's' # return dt_string # # def _default_pad(self, data_type): # ''' # The default pad values by CDF data type # ''' # order = self._convert_option() # if (data_type == 1) or (data_type == 41): # pad_value = struct.pack(order+'b', -127) # elif data_type == 2: # pad_value = struct.pack(order+'h', -32767) # elif data_type == 4: # pad_value = struct.pack(order+'i', -2147483647) # elif (data_type == 8) or (data_type == 33): # pad_value = struct.pack(order+'q', -9223372036854775807) # elif data_type == 11: # pad_value = struct.pack(order+'B', 254) # elif data_type == 12: # pad_value = struct.pack(order+'H', 65534) # elif data_type == 14: # pad_value = struct.pack(order+'I', 4294967294) # elif (data_type == 21) or (data_type == 44): # pad_value = struct.pack(order+'f', -1.0E30) # elif (data_type == 22) or (data_type == 45) or (data_type == 31): # pad_value = struct.pack(order+'d', -1.0E30) # elif (data_type == 32): # pad_value = struct.pack(order+'d', -1.0E30) # elif (data_type == 51) or (data_type == 52): # pad_value = struct.pack(order+'c', ' ') # return pad_value # # def _convert_data(self, data, data_type, num_recs, num_values, num_elems): # ''' # Converts byte stream data of type data_type to a list of data. # ''' # if data_type == 32: # num_values = num_values*2 # # if (data_type == 51 or data_type == 52): # return [data[i:i+num_elems].decode('utf-8') for i in range(0, num_recs*num_values*num_elems, num_elems)] # else: # tofrom = self._convert_option() # dt_string = self._convert_type(data_type) # form = tofrom + str(num_recs*num_values*num_elems) + dt_string # value_len = self._type_size(data_type, num_elems) # return list(struct.unpack_from(form, # data[0:num_recs*num_values*value_len]))
def max_list_iter(int_list): # must use iteration not recursion """finds the max of a list of numbers and returns the value (not the index) If int_list is empty, returns None. If list is None, raises ValueError""" if int_list == []: return None elif int_list is None: raise ValueError else: max_val = 0 for i in int_list: if i > max_val: max_val = i return max_val def reverse_rec(int_list): # must use recursion """recursively reverses a list of numbers and returns the reversed list If list is None, raises ValueError""" if int_list is None: raise ValueError else: if len(int_list) == 1: return int_list else: return reverse_rec(int_list[1:]) + [int_list[0]] def bin_search(target, low, high, int_list): # must use recursion """searches for target in int_list[low..high] and returns index if found If target is not found returns None. If list is None, raises ValueError """ if int_list is None: raise ValueError if high < low: return None mid = (low + high) // 2 if target == int_list[mid]: return mid elif target < int_list[mid]: # target is on the left of mid return bin_search(target, low, mid - 1, int_list) else: # target is on the right of mid return bin_search(target, mid + 1, high, int_list)
import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch import json def phone_num_count(phone_nums): ''' Returns the count of phone numbers in the column. If it is missing return 0 count instead of np.nan Args: ---- phone_nums(str) - phone number in the string form '+91 2232323423\n+91 123233323' or np.nan returns: -------- counts of phone number ''' phones_n = 0 # check for if not NaNs or missing if phone_nums == '0' or phone_nums == 0 or type(phone_nums) == float: return 0 length = 0 # checks for 8 continuos integers and increases the count by 1 for i in range(len(phone_nums)): try: if int(phone_nums[i]): length += 1 if length == 8: phones_n += 1 except: length = 0 #return count, 0 if np.nan else phone counts return phones_n def lower_(x): ''' function takes a string and replcaes the spaces and returns a lower case string Args: ----- x(str) - String input returns: ------- string with no spaces and lower case ''' #Function returns by converting string to lower and removing the spaces if type(x) == str: return x.replace(" ","").lower() def type_x(x,n): ''' function separates the string by comma and returns first index if n = 1 or second index if n = 2 Args: ---- x(str)- comma separated string n - 1 or 2 to return the comma separated string at index 0 or 1 returns ------ returns string at n-1 index from list created by comma separation ''' # function separates the string by comma and returns first index of n = 1 or second index if n = 2 if type(x) == str: #x = x.replace(" ","") x = x.replace(" ","").lower() x = x.split(",") if len(x) >= n: return(x[n-1]) else: return np.nan else: return np.nan def str_to_float(cost): ''' function returns the float value for cost of two Args: ---- cost(str)- string form of cost '1,700' returns ------ returns float value of cost else 500 i.e is the median of the cust_for_two if missing ''' #returns string cost '1,700' as float 1700.0 if type(cost) == str: cost = cost.replace(",","").replace(" ","") return(float(cost)) else: #if np.nan, return median of cost_for_two for the population is 500 return 500 def process(rows,listed_rest_types,listed_rest_city_loc,unique_rest,unique_cuisines,phone_minmax,c_minmax): ''' Function takes in dataframe containing NEW restaurant rows and performs all the preprocesing performed on the train and test data Args: ---- rows(DataFrame) - data frame containing rows of NEW restaurant listed_rest_types(list) - list of 7 unique types of restaurant as mentioned by Zomato for quick search - to form the dummies listed_rest_city_loc(list) - List of 30 locations/zones to fir all the restaurants for quick searches - to form the dummies unique_rest(list) - unique 25 restaurant types as listed by the restaurant on zomato - to form the dummies unique_cuisines(list) - list of 107 unique cusines - to form the dummies phone_minmax(list) - list containing the min and max count of phones in the column phone c_minmax(list) - list containing the min and max count of cost for two returns: -------- processed rows containing 307 columns and all the restaurants having rate as "NEW" ''' rows.drop(columns=['url', 'address','name','rate','votes','menu_item','dish_liked','reviews_list'],inplace = True, errors ='ignore') #calculating number of phones given rows['phone'] = rows.apply(lambda x: (phone_num_count(x.phone) - phone_minmax[0])/(phone_minmax[1] - phone_minmax[0]), axis=1) rows['cost_for_two'] = rows.apply(lambda x: (str_to_float(x.cost_for_two) - c_minmax[0])/(c_minmax[1] - c_minmax[0]) , axis = 1) #dummies for online order # 2 dummy columns created here for noyes in ['no','yes']: column_name1 = 'online_order_'+ noyes #online_order_yes and online_order_no rows[column_name1] = rows.apply(lambda x: 1 if x.online_order.lower() == noyes else 0, axis=1) #print(rows.columns) #dummies for book tabler # 2 dummy columns created here for noyes in ['no','yes']: column_name1 = 'book_table_'+ noyes #book_table_yes and book_table_no dummy created rows[column_name1] = rows.apply(lambda x: 1 if x.book_table.lower() == noyes else 0, axis=1) #print(rows.columns) #creating dummies for restauant listed in 7 types #7 dummy columns created here rows['listed_in_type'] = rows.apply(lambda x: x.listed_in_type.replace(" ","_").lower(), axis = 1) for rest_listed in listed_rest_types: rest_listed = rest_listed.lower().replace(" ","_") column_name1 = 'listed_in_type_'+ rest_listed rows[column_name1] = rows.apply(lambda x: 1 if x.listed_in_type == rest_listed else 0, axis=1) #creating dummies for location listed in 30 types #30 dummy columns created here rows['listed_in_city'] = rows.apply(lambda x: x.listed_in_city.replace(" ","_").lower(), axis = 1) for rest_loc in listed_rest_city_loc: rest_loc = rest_loc.replace(" ","_").lower() column_name1 = 'listed_in_city_'+ rest_loc rows[column_name1] = rows.apply(lambda x: 1 if x.listed_in_city == rest_loc else 0, axis=1) # dropping location of the restaurant rows.drop(columns = ['location','listed_in_city','listed_in_type','online_order','book_table'],inplace = True, axis = 1) #spliting rest types in rest_type separated by comma and storing it in two columns rows['rest_type'] = rows.apply(lambda x: lower_(x.rest_type), axis=1) rows['rest_type1'] = rows.apply(lambda x: type_x(x.rest_type,1), axis=1) rows['rest_type2'] = rows.apply(lambda x: type_x(x.rest_type,2), axis=1) #creating dummies for rest_type1 and rest_type2 listed in 25 types each #50 dummy columns created here for rest in unique_rest: #rest = rest.lower #print(rest) column_name1 = 'rest_type1_'+ rest column_name2 = 'rest_type2_' + rest rows[column_name1] = rows.apply(lambda x: 1 if x.rest_type1 == rest else 0, axis=1) rows[column_name2] = rows.apply(lambda x: 1 if x.rest_type2 == rest else 0, axis=1) #dropping columns after creting dummies rows.drop(columns =['rest_type1','rest_type2','rest_type'],inplace = True) #spliting first two cuisines in cuisines_1 and cuisines_2 separated by comma rows['cuisines'] = rows.apply(lambda x: lower_(x.cuisines), axis=1) rows['cuisines_1'] = rows.apply(lambda x: type_x(x.cuisines,1), axis=1) rows['cuisines_2'] = rows.apply(lambda x: type_x(x.cuisines,2), axis=1) #creating dummies for cuisines_1 and cuisines_2 listed in 107 types each #214 dummy columns created here for cuisine in unique_cuisines: #cuisine = cuisine.lower() column_name1 = 'cuisines_1_'+ cuisine column_name2 = 'cuisines_2_' + cuisine rows[column_name1] = rows.apply(lambda x: 1 if x.cuisines_1 == cuisine else 0, axis=1) rows[column_name2] = rows.apply(lambda x: 1 if x.cuisines_2 == cuisine else 0, axis=1) #dropping columns after creating dumies rows.drop(columns =['cuisines_1','cuisines_2','cuisines'],inplace = True) return rows def predict(model,X): ''' Prints graph for top three predictions with probabilities args: ---- model(NN) : Trained neural network X - processed row to be predicted ''' #freeze the gradients of the model with torch.no_grad(): #remove the dropouts model.eval() #predict prediction = model(X) ps = torch.exp(prediction) #get top 3 prediction top_p, top_class = ps.topk(3) top_p = top_p.cpu().numpy().tolist()[0] top_class = top_class.cpu().numpy().tolist()[0] #print(top_class) with open('rates.json', 'r') as f: class_to_bin = json.load(f) #convert the prediction class to bins in string list_str = [class_to_bin.get(str(int(x))) for x in top_class] #print(list_str,top_p) #plot the probabilties and predicted top bins plt.barh(list_str,top_p) plt.xlabel("probability") plt.ylabel("Prediction class") plt.title("Prediction and probabilities") #print("The Bin Predicted by the model is",list_str[0],"The probability of predicting based on training data is:",top_p[0])
import random __author__ = 'Dmitry Panfilov' # Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: воспользоваться методом .format() print('-- 1 --') lst = ["яблоко", "банан", "киви", "арбуз"] for l in lst: print("{0}.{1:>7}".format(lst.index(l) + 1, l)) # Задача-2: # Даны два произвольные списка. # Удалите из первого списка элементы, присутствующие во втором списке. print('\n-- 2 --') fl = [random.randint(0, 10) for r in range(10)] fs = [random.randint(0, 10) for r in range(10)] print(fl) print(fs) fl = set(fl) - set(fs) print(fl) # Задача-3: # Дан произвольный список из целых чисел. # Получите НОВЫЙ список из элементов исходного, выполнив следующие условия: # если элемент кратен двум, то разделить его на 4, если не кратен, то умножить на два. print('\n-- 3 --') lst = [random.randint(0, 10) for r in range(10)] res = [] for l in lst: if l % 2: res.append(l * 2) else: res.append(l / 4) print(lst) print(res)
import time start_time = time.time() answer = int(input("What is 2+2?\n")) if time.time() - start_time > 10: print("Too slow! You did it in:", round(time.time() - start_time,2), "seconds.") else: if answer == 4: print("Correct! You did it in:", round(time.time() - start_time,2), "seconds.") else: print("Incorrect! The correct answer was 4.")
import tkinter as tk from PIL import Image, ImageTk from tkinter import font as tkFont from tictactoeGUI import ticTacToe as tttGame import configFile as cf import random import time # Initializes main window root = tk.Tk() root.geometry("720x600") root.title("RPG - Bence Redmond") # Creates fonts helv10 = tkFont.Font(family = "Helvetica", size = 10) helv15 = tkFont.Font(family = "Helvetica", size = 15) helv20 = tkFont.Font(family = "Helvetica", size = 17) helv25 = tkFont.Font(family = "Helvetica", size = 25) helv35 = tkFont.Font(family = "Helvetica", size = 35) tooltipList = [] # Function containing all of the tic tac toe code def ticTacToe(): # Initializes main window global tttWindow tttWindow = tk.Toplevel() tttWindow.title("Tic Tac Toe") tttWindow.geometry("425x650") global playerSymbol playerSymbol = "x" # Creates the board # Each upper dictionary represents a row, and each nested dictionary # Represents a column. So if printed (as a board would be) this would output: # Column: # 1 2 3 # _____ # 1 | x o x # Row: 2 | x o x # 3 | x o x board = { 1:{1:"-",2:"-",3:"-"}, 2:{1:"-",2:"-",3:"-"}, 3:{1:"-",2:"-",3:"-"} } # Creates fonts helv25 = tkFont.Font(family = "Helvetica", size = 25) helv50 = tkFont.Font(family = "Helvetica", size = 50) # Initalizes boxes b1 = tk.Button(tttWindow, text = board[1][1], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b1,1,1,playerSymbol)) b2 = tk.Button(tttWindow, text = board[1][2], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b2,1,2,playerSymbol)) b3 = tk.Button(tttWindow, text = board[1][3], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b3,1,3,playerSymbol)) b4 = tk.Button(tttWindow, text = board[2][1], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b4,2,1,playerSymbol)) b5 = tk.Button(tttWindow, text = board[2][2], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b5,2,2,playerSymbol)) b6 = tk.Button(tttWindow, text = board[2][3], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b6,2,3,playerSymbol)) b7 = tk.Button(tttWindow, text = board[3][1], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b7,3,1,playerSymbol)) b8 = tk.Button(tttWindow, text = board[3][2], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b8,3,2,playerSymbol)) b9 = tk.Button(tttWindow, text = board[3][3], font = helv50, padx = 25, pady = 25, command = lambda: changeSymbol(b9,3,3,playerSymbol)) # Creates list of the button objects that can be iterated through later buttonList = [b1, b2, b3, b4, b5, b6, b7, b8, b9] # Creates labels turnLabel = tk.Label(tttWindow, text = f"It is {playerSymbol}'s turn.", font = helv25) label2 = tk.Label(tttWindow, text = "Pick a slot!") # Displays buttons in the 3x3 grid pattern b1.grid(row = 0, column = 0) b2.grid(row = 0, column = 1) b3.grid(row = 0, column = 2) b4.grid(row = 1, column = 0) b5.grid(row = 1, column = 1) b6.grid(row = 1, column = 2) b7.grid(row = 2, column = 0) b8.grid(row = 2, column = 1) b9.grid(row = 2, column = 2) # Displays labels at the bottom of the screen turnLabel.grid(row = 3, column = 0, columnspan = 3) # Displays who's turn it is label2.grid(row = 4, column = 0, columnspan = 3) # Displays smaller misc message # Changes the symbol, takes the button object for modification, x and y for board dict coords, and symbol for the player symbol def changeSymbol(buttonObj, x, y, symbol): if board[x][y] != "-": # Checks if the slot is empty or not label2.config(text = "Invalid Slot!") else: board[x][y] = symbol buttonObj.config(text = board[x][y], state = "disabled") # Sets the button the player clicked to their symbol and disables it if winCheck(board, symbol) == 0: global tttWindow for i in buttonList: # Iterates through the list of button objects i.config(state = "disabled") # Sets each button to disabled label2.config(text = "Close the window to continue!") cf.tttGame_returnVal = symbol tttWindow.destroy() return # Modifies the player's symbol global playerSymbol if symbol == "x": playerSymbol = "o" else: playerSymbol = "x" turnLabel.config(text = f"It is {playerSymbol}'s turn!") def winCheck(board,symbol): # Checks for horizontal wins for i in board: # Creates set of the values in each row rowSet = set(board[i].values()) # As sets cannot contain duplicate values, a row such as "x o x" will become {"x","o"} # We can then check if the row contains only one value (such as {"x"}) and if the value in the set is the player's symbol. if len(rowSet) == 1 and playerSymbol in rowSet: turnLabel.config(text = f"{symbol} wins horizontally!") return 0 # Checks for vertical wins boardSet = set() for i in range(1,4): colSet = set() # Have to use range(1,4) since range(1,3) won't go up to 3 for whatever reason. for row in range(1,4): colSet.add(board[row][i]) boardSet.add(board[row][i]) # Same as above if len(colSet) == 1 and playerSymbol in colSet: turnLabel.config(text = f"{symbol} wins vertically!") return 0 # Checks for diagonal wins diag1 = set(board[1][1]+board[2][2]+board[3][3]) # Top left to bottom right diag2 = set(board[1][3]+board[2][2]+board[3][1]) # Top right to bottom left # Same check system as above if len(diag1) == 1 and playerSymbol in diag1: turnLabel.config(text = f"{symbol} wins diagonally!") return 0 if len(diag2) == 1 and playerSymbol in diag2: turnLabel.config(text = f"{symbol} wins diagonally!") return 0 # Checks for draws using boardSet, which will contain all values in the dictionary if "-" not in boardSet: # Checks if there are any empty slots left turnLabel.config(text = f"It's a draw!") return 0 def guessingGame(): answerNum = random.randint(1,100) print(answerNum) global playerAttempts playerAttempts = 0 global gGame gGame = True def submit(): try: global gGame pAnswer = inputBox.get() pAnswer = int(pAnswer) global playerAttempts playerAttempts += 1 if pAnswer < answerNum: answerLabel.config(text = "Too low!") elif pAnswer > answerNum: answerLabel.config(text = "Too high!") else: answerLabel.config(text = f"Correct! {playerAttempts} guesses.") cf.gGame_returnVal = 1 gGame = False ngWindow.destroy() if playerAttempts >= 10: cf.gGame_returnVal = 0 gGame = False ngWindow.destroy() except: answerLabel.config(text = "Error Encountered! Guess again.") # Initializes main window global ngWindow ngWindow = tk.Toplevel(root) ngWindow.title("Number Guessing Game") ngWindow.geometry("170x130") # Initializes widgets guessingTitle = tk.Label(ngWindow, text = "Guess a Number!", font= helv15) answerLabel = tk.Label(ngWindow, text = "Guess...") inputBox = tk.Entry(ngWindow, width = 20, borderwidth = 4) submitButton = tk.Button(ngWindow, text = "Submit Number", command = submit) # Displays widgets inputBox.grid(row = 2, column = 0) guessingTitle.grid(row = 0, column = 0) answerLabel.grid(row = 1, column = 0) submitButton.grid(row = 3, column = 0) def codeEnter(code): # Initialize main window global ceWindow ceWindow = tk.Toplevel() ceWindow.title("Keypad") ceWindow.geometry("233x320") # Initialize widgets display = tk.Entry(ceWindow, width = 17, borderwidth = 5, font = helv20) display.grid(row = 0, column = 0, columnspan = 3) def button_click(num): newText = display.get() + str(num) display.delete(0, tk.END) display.insert(0, newText) def submit(): print(code) answer = display.get() if answer == "": display.delete(0, tk.END) display.insert(0, "Enter a code!") display.update() time.sleep(2) display.delete(0, tk.END) else: if answer == code: display.delete(0, tk.END) display.insert(0, "Correct!") display.update() time.sleep(2) cf.ceGame_returnVal = "correct" ceWindow.destroy() else: if len(answer) == 4: display.delete(0, tk.END) display.insert(0, "Incorrect!") display.update() time.sleep(2) display.delete(0, tk.END) elif len(answer) < 4: display.delete(0, tk.END) display.insert(0, "Too short!") display.update() time.sleep(2) display.delete(0, tk.END) elif len(answer) > 5: display.delete(0, tk.END) display.insert(0, "Too long!") display.update() time.sleep(2) display.delete(0, tk.END) text = tk.Label(ceWindow, text = "Enter The Code.") button_1 = tk.Button(ceWindow, text = "1", padx = 30, pady = 20, command = lambda: button_click(1)) button_2 = tk.Button(ceWindow, text = "2", padx = 30, pady = 20, command = lambda: button_click(2)) button_3 = tk.Button(ceWindow, text = "3", padx = 30, pady = 20, command = lambda: button_click(3)) button_4 = tk.Button(ceWindow, text = "4", padx = 30, pady = 20, command = lambda: button_click(4)) button_5 = tk.Button(ceWindow, text = "5", padx = 30, pady = 20, command = lambda: button_click(5)) button_6 = tk.Button(ceWindow, text = "6", padx = 30, pady = 20, command = lambda: button_click(6)) button_7 = tk.Button(ceWindow, text = "7", padx = 30, pady = 20, command = lambda: button_click(7)) button_8 = tk.Button(ceWindow, text = "8", padx = 30, pady = 20, command = lambda: button_click(8)) button_9 = tk.Button(ceWindow, text = "9", padx = 30, pady = 20, command = lambda: button_click(9)) button_0 = tk.Button(ceWindow, text = "0", padx = 30, pady = 20, command = lambda: button_click(0)) submit = tk.Button(ceWindow, text = "Submit", padx = 53, pady = 20, command = submit) button_1.grid(row=3, column=0) button_2.grid(row=3, column=1) button_3.grid(row=3, column=2) button_4.grid(row=2, column=0) button_5.grid(row=2, column=1) button_6.grid(row=2, column=2) button_7.grid(row=1, column=0) button_8.grid(row=1, column=1) button_9.grid(row=1, column=2) button_0.grid(row=4, column=0) submit.grid(row=4, column=1, columnspan=2) text.grid(row = 5, column = 0, columnspan = 4) def displayEnd(ending, endingNo): global endScreen # Creates the end screen window endScreen = tk.Toplevel(root) endName = ending["name"] endScreen.title(f"New Ending - {endName}") endScreen.geometry("550x150") # Updates the player's end dictionary player.unlockEnding(endingNo) # Creates the labels endName_label = tk.Label(endScreen, text = f"Ending Reached - {endName}", font = helv25) endText_label = tk.Label(endScreen, text = ending["text"], font = helv15) end2Text_label = tk.Label(endScreen, text = f"You've now unlocked {player.unlockedEndings}/{len(player.endDict)} endings.") restartButton = tk.Button(endScreen, text = "Restart Game", command = lambda: player.resetGame(endScreen), font = helv20) # Button to restart the game # Displays widgets endName_label.grid(row = 0, column = 0, sticky = "w") endText_label.grid(row = 2, column = 0, sticky = "w") end2Text_label.grid(row = 1, column = 0, sticky = "w") restartButton.grid(row = 3, column= 0, sticky = "w") def wineGuesser(): # Python garbage collector goes ahead and gets rid of the image variables if they are local for whatever reason global wgWindow, wine1_img, wine2_img, wine3_img wgWindow = tk.Toplevel() wgWindow.title("Wine Guesser") wgWindow.geometry("500x300") def submit(choice): if choice == random.randint(1,3): descLabel.config(text = "You died! Ahhh.") descLabel.update() time.sleep(2) wgWindow.destroy() cf.wgGame_returnVal = 0 else: descLabel.config(text = "You chose the wine. Nice job!") descLabel.update() time.sleep(2) wgWindow.destroy() cf.wgGame_returnVal = 1 titleLabel = tk.Label(wgWindow, text = "Wine Guesser", font = helv25) descLabel = tk.Label(wgWindow, text = "Choose a poi- wine. Be careful now.", font = helv15) # Create wine bottles preWine1_img = Image.open("winebottle1.png") preWine1_img = preWine1_img.resize((60, 90), Image.ANTIALIAS) wine1_img = ImageTk.PhotoImage(preWine1_img) preWine2_img = Image.open("winebottle2.png") preWine2_img = preWine2_img.resize((60, 90), Image.ANTIALIAS) wine2_img = ImageTk.PhotoImage(preWine2_img) preWine3_img = Image.open("winebottle3.png") preWine3_img = preWine3_img.resize((60, 90), Image.ANTIALIAS) wine3_img = ImageTk.PhotoImage(preWine3_img) # Creates image labels wine1 = tk.Button(wgWindow, image = wine1_img, command = lambda: submit(1)) wine2 = tk.Button(wgWindow, image = wine2_img, command = lambda: submit(2)) wine3 = tk.Button(wgWindow, image = wine3_img, command = lambda: submit(3)) titleLabel.grid(row = 0, column = 0, sticky = "w", columnspan = 3) descLabel.grid(row = 1, column = 0, sticky = "w", columnspan = 3) wine1.grid(row = 2, column = 0) wine2.grid(row = 2, column = 1) wine3.grid(row = 2, column = 2) def multipleChoice(): global mcWindow, questionNo, correctAnswer # Sets up the window mcWindow = tk.Toplevel() mcWindow.title("Quiz") mcWindow.geometry("600x200") questionNo = 0 correctAnswer = 0 # Dictionary to store the questions (q), answers (answers), and correct answer number (c). questionsDict = {1:{"q":"How old am I?", "answers":{1:"I don't know", 2:"INT", 3:"FLOAT", 4:"14"}, "c":4}, 2:{"q":"What's my name?","answers":{1:"James",2:"Dolt",3:"Bence",4:"Arthur"},"c":3}, 3:{"q":"What programming language are Operating Systems coded in?","answers":{1:"C",2:"Python",3:"Scratch",4:"Java"},"c":1}, 4:{"q":"What is the lowest level programming language?","answers":{1:"Assembly",2:"Factory",3:"C",4:"JVM"}, "c":1}, 5:{"q":"What programming language are websites made in?","answers":{1:"C",2:"Javascript",3:"Java",4:"Python"}, "c":2}, 6:{"q":"What programming language is used for data science?","answers":{1:"Javascript",2:"Java",3:"Python",4:"Java"}, "c":3} } # Read start() first, most variables are initialized there def submit(answer): global qName, qDesc, questionNo, correctAnswer try: if answer == questionsDict[qList[questionNo]]["c"]: print("Correct!") correctAnswer += 1 qDesc.config(text = "Correct!") else: print("Incorrect!") qDesc.config(text = "Incorrect!") questionNo += 1 qName.config(text = questionsDict[qList[questionNo]]["q"]) for i in range(1,5): buttonDict[i].config(text = questionsDict[qList[questionNo]]["answers"][i]) except KeyError: qDesc.config(text = "End of Game!") qName.config(text = f"You got: {correctAnswer}/{len(qList)}") qDesc.update() qName.update() for i in range(1,5): buttonDict[i].config(state = "disabled") time.sleep(2) if correctAnswer >= len(questionsDict)/2: cf.mcGame_returnVal = 1 else: cf.mcGame_returnVal = 0 mcWindow.destroy() except IndexError: qDesc.config(text = "End of Game!") qName.config(text = f"You got: {correctAnswer}/{len(qList)}") qDesc.update() qName.update() for i in range(1,5): buttonDict[i].config(state = "disabled") time.sleep(2) if correctAnswer >= len(questionsDict)/2: cf.mcGame_returnVal = 1 else: cf.mcGame_returnVal = 0 mcWindow.destroy() title = tk.Label(mcWindow, text = "Multiple Choice Quiz", font = helv25) a1 = tk.Button(mcWindow, font = helv10, command = lambda: submit(1)) a2 = tk.Button(mcWindow, font = helv10, command = lambda: submit(2)) a3 = tk.Button(mcWindow, font = helv10, command = lambda: submit(3)) a4 = tk.Button(mcWindow, font = helv10, command = lambda: submit(4)) a1.grid(row = 3, column = 0) a2.grid(row = 3, column = 1) a3.grid(row = 3, column = 2) a4.grid(row = 3, column = 3) buttonDict = {1:a1,2:a2,3:a3,4:a4} def start(): global qName, qDesc, qList qList = list(range(1,len(questionsDict)+1)) # Creates a list from 1 - to the length of the list for i in range(len(qList)-3): # Pops all values except for three. popNo = random.randint(0,len(qList)-1) print(f"Pop: {popNo} || Length: {len(qList)} || List: {qList}") qList.pop(popNo) qName = tk.Label(mcWindow, text = questionsDict[qList[0]]["q"], font = helv15) qName.grid(row = 2, column = 0, sticky = "w", columnspan = 5) qDesc = tk.Label(mcWindow, text = "Make your choice!",font = helv15) qDesc.grid(row = 1, column = 0, sticky = "w", columnspan = 5) for i in range(1,5): buttonDict[i].config(text = questionsDict[qList[0]]["answers"][i]) title.grid(row = 0, column = 0, columnspan = 4) start() def doorGuesser(): # Python garbage collector goes ahead and gets rid of the image variables if they are local for whatever reason global dgWindow, door1_img, door2_img, door3_img dgWindow = tk.Toplevel() dgWindow.title("Door Guesser") dgWindow.geometry("500x300") def submit(choice): if choice in [1,3]: descLabel.config(text = "Wrong door! Try again.") descLabel.update() time.sleep(2) dgWindow.destroy() cf.dgGame_returnVal = 0 else: descLabel.config(text = "You chose the right door. Nice job!") descLabel.update() time.sleep(2) dgWindow.destroy() cf.dgGame_returnVal = 1 titleLabel = tk.Label(dgWindow, text = "Door Guesser", font = helv25) descLabel = tk.Label(dgWindow, text = "Choose the right door. May or may not lead to death.", font = helv15) # Create doors preDoor1_img = Image.open("door1.png") preDoor1_img = preDoor1_img.resize((60, 90), Image.ANTIALIAS) door1_img = ImageTk.PhotoImage(preDoor1_img) preDoor2_img = Image.open("door2.jpg") preDoor2_img = preDoor2_img.resize((60, 90), Image.ANTIALIAS) door2_img = ImageTk.PhotoImage(preDoor2_img) preDoor3_img = Image.open("door3.png") preDoor3_img = preDoor3_img.resize((60, 90), Image.ANTIALIAS) door3_img = ImageTk.PhotoImage(preDoor3_img) # Creates image labels door1 = tk.Button(dgWindow, image = door1_img, command = lambda: submit(1)) door2 = tk.Button(dgWindow, image = door2_img, command = lambda: submit(2)) door3 = tk.Button(dgWindow, image = door3_img, command = lambda: submit(3)) titleLabel.grid(row = 0, column = 0, sticky = "w", columnspan = 3) descLabel.grid(row = 1, column = 0, sticky = "w", columnspan = 3) door1.grid(row = 2, column = 0) door2.grid(row = 2, column = 1) door3.grid(row = 2, column = 2) def keyGet(): global kgWindow, key_img kgWindow = tk.Toplevel() kgWindow.title("Item get!") kgWindow.geometry("300x220") title = tk.Label(kgWindow, text = "Item Get!", font = helv25) subText = tk.Label(kgWindow, text = "You picked up a key!", font = helv20) exitButton = tk.Button(kgWindow, text = "Exit", font = helv15, command = kgWindow.destroy) preKey_img = Image.open("key.png") preKey_img = preKey_img.resize((150, 90), Image.ANTIALIAS) key_img = ImageTk.PhotoImage(preKey_img) keyLabel = tk.Label(kgWindow, image = key_img) title.grid(row = 0, column = 0, sticky = "w") subText.grid(row = 1, column = 0, sticky = "w") keyLabel.grid(row = 2, column = 0, sticky = "w") exitButton.grid(row = 3, column = 0, sticky = "w") player.keyGot = 1 def lock(): global lWindow, lock_img lWindow = tk.Toplevel() lWindow.title("Lock") lWindow.geometry("300x300") def unlock(): if player.keyGot == 1: cf.lGame_returnVal = 1 lWindow.destroy() else: subText.config(text = "You don't seem to have the key!") subText.update() title = tk.Label(lWindow, text = "Lock!", font = helv25) subText = tk.Label(lWindow, text = "Hmm... do you have a key?", font = helv15) preLock_img = Image.open("lock.png") preLock_img = preLock_img.resize((150, 150), Image.ANTIALIAS) lock_img = ImageTk.PhotoImage(preLock_img) lockImg = tk.Button(lWindow, image = lock_img, command = unlock) title.grid(row = 0, column = 0, sticky = "w") subText.grid(row = 1, column = 0, sticky = "w") lockImg.grid(row = 2, column = 0, sticky = "w") def winScene(): global fWindow fWindow = tk.Toplevel() fWindow.title("The End") fWindow.geometry("400x200") titleLabel = tk.Label(fWindow, text = "The End.", font = helv35) subText = tk.Label(fWindow, text = "Congratulations on finishing the game!", font = helv20) author = tk.Label(fWindow, text = "'RPG' by Bence Redmond") exitButton = tk.Button(fWindow, text = "Exit", font = helv20, command = fWindow.destroy) titleLabel.grid(row = 0, column = 0, sticky = "w") subText.grid(row = 2, column = 0, sticky = "w") author.grid(row = 1, column = 0, sticky = "w") exitButton.grid(row = 3, column = 0, sticky = "w") class ToolTip(object): # Throws a lot of errors but works fine def __init__(self, widget, text): self.widget = widget self.text = text def enter(event): self.showTooltip() def leave(event): self.hideTooltip() widget.bind('<Enter>', enter) widget.bind('<Leave>', leave) def showTooltip(self): if self.widget["state"] != "disabled": self.tooltipwindow = tw = tk.Toplevel(self.widget) tw.wm_overrideredirect(1) # Window without border and no normal means of closing tw.wm_geometry("+{}+{}".format(self.widget.winfo_rootx(), self.widget.winfo_rooty())) # Sets size of tooltip label = tk.Label(tw, text = self.text, background = "#ffffe0", relief = 'solid', borderwidth = 1) label.pack() tooltipList.append(self) def hideTooltip(self): for i in tooltipList: if i.widget["state"] == "disabled": i.tooltipwindow.destroy() tooltipList.remove(self) if self.widget["state"] != "disabled" or type(self.tooltipwindow) == "tkinter.TopLevel": if self in tooltipList: self.tooltipwindow.destroy() tooltipList.remove(self) self.tooltipwindow = None # Class to store player information class playerState(): def __init__(self, room, lives): self.room = room # Stores current room as an object self.lives = lives self.unlockedEndings = 0 # Dictionary to store different end conditions self.endDict = {0:{"name":"Death", "unlocked":False, "text":"Expected to be honest.", "room":"N/A", "c":"None!"}, 1:{"name":"Awkward...","unlocked":False, "text":"Well, you weren't supposed to do that.", "room":"Doorway", "c":"1"}, 2:{"name":"Scaredy Cat","unlocked":False, "text":"Hide from your fears.", "room":"Closet", "c":"9"}, 3:{"name":"Relaxation Time","unlocked":False,"text":"Sometimes you just need to sit back and relax.","room":"Theatre", "c":"7"}, 4:{"name":"Tasty!","unlocked":False, "text":"Too much food...","room":"Food Closet","c":"6"} } self.code = ["-","-","-","-"] self.keyGot = 0 def loseLife(self, lost): self.heartDict[self.lives].config(image = emptyHeart_img) self.lives -= lost if self.lives <= 0: displayEnd(player.endDict[0], 0) self.unlockEnding(0) self.lives = 3 for i in range(1,4): self.heartDict[i].config(image = heart_img) def resetGame(self, destroyWindow): # Closes the end screen window destroyWindow.destroy() # Resets the the rooms' text and puzzles createRooms() createNeighbours() player.room = startingRoom # Reloads the "map" startingRoom.initState() def unlockEnding(self, ending): # Checks if the ending has already been unlocked if self.endDict[ending]["unlocked"] != True: self.unlockedEndings += 1 self.endDict[ending].update({"unlocked":True}) if ending - 1 >= 0: self.code[ending-1] = self.endDict[ending]["c"] # Class used to create the rooms class room(): def __init__(self, puzzle, name, text, winText, loseText, code = 0): self.name = name self.puzzle = puzzle self.text = text # Text to display when the player enters a room self.loseText = loseText self.winText = winText self.code = code def assignNeighbours(self, left, right, up, down): # Stores the information about the room's neighbours, and the button object that leads to that room self.neighbours = {"left":{"button":leftArrow, "room":left}, "right":{"button":rightArrow, "room":right}, "up":{"button":upArrow, "room":up}, "down":{"button":downArrow, "room":down}} # Loads the room def initState(self): global secondLabel, interactButton, roomLabel, roomText # Edits the text to the appropriate room's roomLabel.config(text = player.room.name) roomText.config(text = player.room.text) # List to iterate through later dictList = ["left","right","up","down"] print("Initialized") for i in dictList: neighbour = self.neighbours[i] # Ease of access if neighbour["room"] == False: # Checks if there is a neighbouring room in that direction neighbour["button"].grid_remove() # neighbour["button"].config(state = "disabled", bg = "#ff8080") else: # If not, loads appropriately neighbour["button"].grid() if self.puzzle == "fin": # Checks if the player has completed the puzzle neighbour["button"].config(state = "active", bg = "white") idToolTip = ToolTip(neighbour["button"], text = neighbour["room"].name) print(idToolTip) else: if neighbour["room"].puzzle == "fin": neighbour["button"].config(state = "active", bg = "white") else: neighbour["button"].config(state = "disabled", bg = "#ff8080") if self.puzzle != "fin": # Checks to see if the interact button needs to be locked or not interactButton.config(state = "active", bg = "white") else: interactButton.config(state = "disabled", bg = "#ff8080") def moveRoom(self, direction): global roomLabel, roomText, tooltipList for i in tooltipList: i.tooltipwindow.destroy() tooltipList = [] player.room = self.neighbours[direction]["room"] # Sets the player's current room to the room at that given direction roomLabel.config(text = player.room.name) roomText.config(text = player.room.text) player.room.initState() # Handles puzzle loading and outcome determination def interact(self): global interactButton, roomText interactButton.config(state = "disabled") if player.room.puzzle == "gGame": guessingGame() root.wait_window(ngWindow) # Pauses the following code until the game window has been closed returnVal = cf.gGame_returnVal # Ease of use if returnVal == 1: player.room.text = player.room.winText roomText.config(text = player.room.text) # Edits the room text to be the win text interactButton.config(state = "active") player.room.puzzle = "fin" cf.gGame_returnVal = -1 # Resets cf.gGame_returnVal for future games (after in-game restart) elif returnVal == 0: interactButton.config(state = "disabled") player.room.text = player.room.loseText roomText.config(text = player.room.text) player.loseLife(1) player.room.initState() cf.gGame_returnVal = -1 elif player.room.puzzle == "ttt": # Follows same principles as above ticTacToe() root.wait_window(tttWindow) returnVal = cf.tttGame_returnVal if returnVal == "x": player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.puzzle = "fin" elif returnVal == "o": player.room.text = player.room.loseText roomText.config(text = player.room.text) interactButton.config(state = "active") else: interactButton.config(state = "active") cf.tttGame_returnVal = 0 player.room.initState() elif player.room.puzzle == "code": codeEnter(player.room.code) root.wait_window(ceWindow) returnVal = cf.ceGame_returnVal if returnVal == "correct": player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.puzzle = "fin" player.room.initState() elif player.room.puzzle == "wGame": wineGuesser() root.wait_window(wgWindow) returnVal = cf.wgGame_returnVal if returnVal == 1: player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.puzzle = "fin" else: interactButton.config(state = "disabled") player.room.text = player.room.loseText roomText.config(text = player.room.text) player.loseLife(1) cf.wgGame_returnVal = -1 player.room.initState() elif player.room.puzzle == "mc": multipleChoice() root.wait_window(mcWindow) returnVal = cf.mcGame_returnVal if returnVal == 1: player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.puzzle = "fin" else: interactButton.config(state = "disabled") player.room.text = player.room.loseText roomText.config(text = player.room.text) player.loseLife(1) cf.mcGame_returnVal = -1 player.room.initState() elif player.room.puzzle == "end": winScene() root.wait_window(fWindow) root.destroy() elif player.room.puzzle == "door": doorGuesser() root.wait_window(dgWindow) returnVal = cf.dgGame_returnVal if returnVal == 1: player.room.text = player.room.winText roomText.config(text = player.room.text) keyGet() root.wait_window(kgWindow) player.room.puzzle = "fin" else: interactButton.config(state = "disabled") player.room.text = player.room.loseText roomText.config(text = player.room.text) player.loseLife(1) cf.dgGame_returnVal = -1 player.room.initState() elif player.room.puzzle == "lock": lock() root.wait_window(lWindow) returnVal = cf.lGame_returnVal if returnVal == 1: player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.puzzle = "fin" else: interactButton.config(state = "disabled") player.room.text = player.room.loseText roomText.config(text = player.room.text) player.room.initState() elif player.room.puzzle == "none": player.room.puzzle = "fin" player.room.text = player.room.winText roomText.config(text = player.room.text) player.room.initState() else: # If the puzzle is not any of the above, then it must be an ending. displayEnd(player.endDict[player.room.puzzle], player.room.puzzle) def createRooms(): # room() takes the puzzle, name of room, text to display when the player enters, text to display when the players loses/wins. global startingRoom, hallway1, doorway, kitchen, ballroom, hallway2, bossroom, slide, stairs1, basement, closet, stairs2, cellar, theatre, dining_room, hallway3, kitchen, closet2, hallway4, living_room startingRoom = room("gGame", "Entrance", "Ho ho ho... welcome to my house of Death!", "Hmm, maybe that was a bit too easy.", "Well that was a good effort... down one life!", "1976") hallway1 = room("ttt", "Hallway", "You see a whiteboard on the wall, with a Tic Tac Toe board. Let's play!", "I would have been worried if you hadn't won that.", "How did you... lose against yourself?") doorway = room(1, "Doorway", "Well, I guess you win?", "N/A", "N/A") ballroom = room("mc", "Ballroom", "Pop quiz! No dancing or music unfortunately.", "Maybe I should have made the questions a bit harder.", "You should brush up on your trivia.") hallway2 = room("code", "Hallway", "You here a faint hum ahead. Spooky.", "There's no turning back once you go forward.", "Go and explore more. Open up the endings screen to see what you have so far.", "1976") bossroom = room("end", "The Exit", "Damn you!", "Begone fool...", "Muahahaha! Try again.") slide = room("none", "Slide!", "Down you go!", "N/A", "N/A") stairs1 = room("gGame", "Basement Stairs", "The stairs lead down to a very dark room.", "I should stop using these number guessing games.", " Get good.") basement = room("none", "Basement", "Ahhhh! I'm joking. Why would I get scared in my own house?", "Well, you've still got a ways to go.", "Hahahahaha.") closet = room(2, "Closet", "Just hide and everything will be alright.", "N/A", "N/A") stairs2 = room("door", "Deeper Stairs", "These lead deeper down...", "Good luck in the next room. Hehehe...", "Come on. You just have to pick a door.") cellar = room("wGame", "Wine Cellar", "Ah, a proud collection. Don't touch anything!", "That was expensive...", "Serves you right!") theatre = room(3, "Theatre", "Sometimes it's nice to relax with some popcorn and watch a movie.", "N/A", "N/A") dining_room = room("none", "Dining Room", "Good luck finding your way through this maze of tables.", "What do you mean it was just a restaurant?.", "If you stick to the right it might work.") hallway3 = room("ttt", "Hallway", "Maybe this will stump you.", "Well, congrats. You've done the bare minimum.", "How...?") kitchen = room("none", "Kitchen", "Let's test your cooking skills.", "Ah... I may have forgotten to lay out the food. Forget this.", "How many times have you cooked in your life?") closet2 = room(4, "Food Closet", "Eat your problems away.", "N/A", "N/A") hallway4 = room("lock", "Hallway", "Good luck picking this!", "Darn it. I paid a lot for that lock.", "Hahah! Wait... where did I put that key?") living_room = room("none", "Living Room", "Let's watch some TV and relax.", "Do you mind getting some food?","Have you never used a remote in your life?") def createNeighbours(): global startingRoom, hallway1, doorway, kitchen # Assigns the room's neighbours as room objects # assignNeighbours(Left, Right, Up, Down) startingRoom.assignNeighbours(False, False, hallway1, doorway) doorway.assignNeighbours(False, False, startingRoom, False) hallway1.assignNeighbours(False, False, ballroom, startingRoom) ballroom.assignNeighbours(stairs1, dining_room, hallway2, hallway1) hallway2.assignNeighbours(slide, False, bossroom, ballroom) bossroom.assignNeighbours(False, False, False, hallway2) slide.assignNeighbours(basement, False, False, False) stairs1.assignNeighbours(basement, ballroom, False, False) basement.assignNeighbours(False, stairs1, closet, stairs2) closet.assignNeighbours(False, False, False, basement) stairs2.assignNeighbours(False, False, basement, cellar) cellar.assignNeighbours(False, theatre, stairs2, False) theatre.assignNeighbours(cellar, False, False, False) dining_room.assignNeighbours(ballroom, False, hallway3, hallway4) hallway3.assignNeighbours(False, False, kitchen, dining_room) kitchen.assignNeighbours(False, False, closet2, hallway3) closet2.assignNeighbours(False, False, False, kitchen) hallway4.assignNeighbours(False, False, dining_room, living_room) living_room.assignNeighbours(False, False, hallway4, False) createRooms() player = playerState(startingRoom, 3) # Handles the ending screen window def endingsScreen(endings): global endingsButton endingsButton.config(state = "disabled") endingsWin = tk.Toplevel() endingsWin.title("Your Unlocked Endings") endingsWin.geometry("650x500") codeText = "".join(player.code) endingsTitle = tk.Label(endingsWin, font = helv35, text = f"All Endings || {player.unlockedEndings}/{len(endings)} Unlocked") codeLabel = tk.Label(endingsWin, font = helv25, text = f"Code: {codeText}\n---------------------------------------") row = 2 # Used to iterate through the ending dictionary, and display each value there # This system doesn't require me to come back and edit when I need to add new endings for i in range(0,len(endings)): print(endings[i]) tempTitle = tk.Label(endingsWin, text = endings[i]["name"], font = helv25, anchor = "w") tempLabel = tk.Label(endingsWin, text = f"Unlocked: {endings[i]['unlocked']} || {endings[i]['text']}") tempTitle.grid(row = row, column = 0, sticky = "w") tempLabel.grid(row = row + 1, column = 0, sticky = "w") row += 2 endingsTitle.grid(row = 0, column = 0, columnspan = 2, sticky = "w") codeLabel.grid(row = 1, column = 0, columnspan = 2, sticky = "w") root.wait_window(endingsWin) # Waits until the player closes the ending screen endingsButton.config(state = "active") def displayMenu(): global endingsButton, restartButton menuWindow = tk.Toplevel() menuWindow.geometry("220x200") menuTitle = tk.Label(menuWindow, text = "Menu", font = helv35) endingsButton = tk.Button(menuWindow, text = "Unlocked Endings", font = helv20, command = lambda: endingsScreen(player.endDict)) restartButton = tk.Button(menuWindow, text = "Restart", font = helv20, command = lambda: player.resetGame(menuWindow)) menuTitle.pack() endingsButton.pack() restartButton.pack() # Initializes main images preHeart_img = Image.open("heart.png") preHeart_img = preHeart_img.resize((60, 60), Image.ANTIALIAS) preEmptyHeart_img = Image.open("emptyHeart.png") preEmptyHeart_img = preEmptyHeart_img.resize((60, 60)) emptyHeart_img = ImageTk.PhotoImage(preEmptyHeart_img) heart_img = ImageTk.PhotoImage(preHeart_img) # Creates the heart labels heart1 = tk.Label(root, image = heart_img, anchor = "w") heart2 = tk.Label(root, image = heart_img, anchor = "w") heart3 = tk.Label(root, image = heart_img, anchor = "w") player.heartDict = {1:heart1, 2:heart2, 3:heart3} # Creates main text roomLabel = tk.Label(root, text = player.room.name, font = helv35) roomText = tk.Label(root, text = player.room.text, font = helv20) secondLabel = tk.Label(root, text = "Choose a direction to go:", font = helv15) # Creates buttons menuButton = tk.Button(root, text = "Menu", font = helv25, borderwidth = 5, command = displayMenu) upArrow = tk.Button(root, bg = "#ff8080", width = 6, height = 3, state = "disabled", text = "^", font = helv15, command = lambda: player.room.moveRoom("up")) leftArrow = tk.Button(root, bg = "#ff8080", width = 6, height = 3, state = "disabled", text = "<", font = helv15, command = lambda: player.room.moveRoom("left")) downArrow = tk.Button(root, bg = "#ff8080", width = 6, height = 3, state = "disabled", text = "v", font = helv15, command = lambda: player.room.moveRoom("down")) rightArrow = tk.Button(root, bg = "#ff8080", width = 6, height = 3, state = "disabled", text = ">", font = helv15, command = lambda: player.room.moveRoom("right")) interactButton = tk.Button(root, bg = "#ff8080", width = 6, height = 3, state = "disabled", text = "x", font = helv15, command = player.room.interact) # Creates empty canvas spaces topCanvas = tk.Canvas(root, width = 140, height = 10) # Displays the created widgets heart1.grid(row = 0, column = 0) heart2.grid(row = 0, column = 1) heart3.grid(row = 0, column = 2) roomLabel.grid(row = 0, column = 3, padx = 20) secondLabel.grid(row = 2, column = 0, columnspan = 3) topCanvas.grid(row = 0, column = 4, columnspan = 1) roomText.grid(row = 1, column = 0, columnspan = 8, sticky = "w") upArrow.grid(row = 3, column = 1) leftArrow.grid(row = 4, column = 0) downArrow.grid(row = 5, column = 1) rightArrow.grid(row = 4, column = 2) interactButton.grid(row = 4, column = 1) menuButton.grid(row = 0, column = 5) createNeighbours() startingRoom.initState() root.mainloop() # Starts main window
import os import random import colorama from colorama import Fore, Back, Style, init init() def cls(): return os.system('cls') cls() name = input("Type your name here: ") print(f"You have {len(name)} letters in your name ") print("The letters of your name are:") for x in range(len(name)): if x % 2 == 0: print(f"{Fore.RED} {name[x]}", end="") else: print(f"{Fore.GREEN} {name[x]}", end="")
import random import os from colorama import init from colorama import Fore, Back, Style, init init() def cls(): return os.system('cls') cls() def printRed(s): print(f"{Fore.RED}{s}{Style.RESET_ALL}") def printYellow(s): print(f"{Fore.YELLOW}{s}{Style.RESET_ALL}", end="") def inputBlue(s): return f"{s}{Fore.BLUE}" countries = ["germany", "canada", "italy", "ecuador", "argentina", "greece", "israel", "england", "japan", "korea", "australia", "brazil", "portugal", "egypt", "kenya", "holland", "peru", "poland", "france", "sweden"] randomIndex = random.randint(0, len(countries)-1 ) #length secretCountry = countries[randomIndex] dashes =[] for x in secretCountry: dashes.append(" - ") # for x in secretCountry: # print(f" {x} ", end="") print() for dash in dashes: printYellow(dash) letter="" while " - " in dashes: print() letter = input("type your letter: ") if letter in secretCountry: for a in range(): if secretCountry[a]==letter: dashes[a]=letter+" " for dash in dashes: printYellow(dash) print("AMAZING!!!")
class Boardposs : def __init__(self,player1 = 'X', player2 = 'O'): self.size = {'c' : 7, 'r': 6} # 7 columns x 6 rows self.grid = [] self.first_player = True # True - player 1 on the move, False - player 2 on the move self.players = {True : player1, False : player2} # Anything except ? (question mark) AND 1 character only! self.game_over = False self.grid = [[] for i in range(self.size['c'])] self.pos=None self.player=None self.inserted_row=None self.a=None # Returns True if disc was successfully dropped, False otherwise def drop(self, column): # Drop a disc into a column if self.game_over: return False # Cannot proceed because game has already ended. if column < 0 or column >= self.size['c']: return False if len(self.grid[column]) >= self.size['r']: return False self.pos=column self.grid[column].append(self.players[self.first_player]) #print("column lenhth :",len(self.grid[column])) self.inserted_row=len(self.grid[column])-1 #print(column) #print(self.inserted_row) #print("inserted_row in drop = ",self.inserted_row) c = self.check() if c == False: self.first_player = not self.first_player return True else: self.game_over = c return True """ def change_vals(self,pos,player): global inserted_row for i in range(5,-1,-1): if(self.a[i][self.pos]==0): self.a[i][self.pos]=player inserted_row = i #print("hello",inserted_row) break elif(self.a[0][self.pos]==1): print("Invalid") break for i in range(0,6): print(self.a[i]) """ def check(self): #print((self.grid)) #up self.a=[[0 for i in range(0,7)] for j in range(0,6)] pl_var=self.players[self.first_player] if(pl_var=='X'): self.player=1 elif(pl_var=='O'): self.player=2 #horizontal for i,column in enumerate(self.grid): #print(i,len(j)) #i=6-i #Down #if(len(column)==4): # return True #j is each column k=0 for j in column: if(j=='X'): self.a[k][i]=1 #self.player=1 elif(j=='O'): self.a[k][i]=2 #self.player=2 k+=1 #horizontal #print(self.a) #print(self.a) for i in range(5,-1,-1): print(self.a[i]) print("current row ",self.inserted_row, " current pos ",self.pos) #print("row 0",self.a[self.inserted_row]) #diagpnal1 #diagonal2 #print("Player",self.player) #use set() to check #self.inserted_row-=1 counter=0 #print("inserted_row in check",self.inserted_row) for i in range(self.pos,-1,-1): #left #print("a[-1][0]",self.a[-1][0]) #print("value","player","pos",self.a[self.inserted_row][i],self.player,self.pos) if(self.a[self.inserted_row][i]==self.player): counter+=1 else: break for i in range(self.pos+1,7): #right #print(self.a[self.inserted_row][i],self.player) if(self.a[self.inserted_row][i]==self.player): counter+=1 else: break #print("hori counter:",counter) if(counter>=4): print("Player ",self.player," won : LEFT-RIGHT") #exit(0) return True else: counter=0 for i in range(self.inserted_row,6): #up if(self.a[i][self.pos]==self.player): counter+=1 else: break for i in range(self.inserted_row-1,-1,-1): #down if(self.a[i][self.pos]==self.player): counter+=1 else: break #print("verti counter:",counter) if(counter>=4): print("Player ",self.player," won : UP-DOWN") #exit(0) return True else: counter=0 #print("Pos ",pos," Row ",inserted_row) pos_diag=self.pos for i in range(self.inserted_row,-1,-1): #45-degree diagonal right if(pos_diag<7 and self.a[i][pos_diag]==self.player): pos_diag+=1 counter+=1 #print("hi") #print("45 deg",counter) else: break #print("counter after 1st for loop",counter) pos_diag=self.pos-1 for i in range(self.inserted_row+1,6): #45-degree diagonal left #print("row ",i," column ",pos_diag) #print("pos_diag","player",self.a[i][pos_diag],self.player) if(pos_diag>=0 and self.a[i][pos_diag]==self.player ): pos_diag-=1 counter+=1 #print("45 deg",counter) else: break if(counter>=4): print("Player ",self.player," won : NEG_DIAG") #exit(0) return True else: counter=0 #print("Pos ",pos," Row ",inserted_row) pos_diag=self.pos for i in range(self.inserted_row,-1,-1): #135-degree diagonal left if( pos_diag>=0 and self.a[i][pos_diag]==self.player): pos_diag-=1 counter+=1 #print("hi") #print("135",counter) else: break #print("counter after 1st for loop",counter) pos_diag=self.pos+1 for i in range(self.inserted_row+1,6): #135-degree diagonal right #print("row ",i," column ",pos_diag) if(pos_diag<7 and self.a[i][pos_diag]==self.player ): pos_diag+=1 counter+=1 #print("135",counter) else: break #print("135 deg",counter) if(counter>=4): print("Player ",self.player," won : NEG_DIAG") #exit(0) return True return False """ op=Boardposs() while(1): print("Player Position") player, pos = input().split(" ") player = int(player) pos = int(self.pos) ip=op.change_vals(self.pos,player) op.check_for_win(self.pos,player) """ #135 diag not working in middle
""" Print the sum of digits in 100! This is a very easy question , I choose to learn python functional programming features from this I have used reduce(x, y, z) x is a binary operator that returns a value y is an iterable object (list, generator .... ) z is the starting value. For example x = mul y = [10, 20, 30] z = 1 reduce(x, y, z) = (((1 * 10) * 20) * 30) sum is short for reduce(add, y, 0) """ from operator import mul print sum(int(z) for z in str(reduce (mul , xrange(1, 101), 1)))
#Andreu Pomar Cabot #Ejercicio 7.4 - Cambiar espacios de un str por * def estrella(): final = frase.replace(" ","*") return final frase = str(input("Introduzca una frase con espacios: ")) final = estrella() print (final)
#Andreu Pomar Cabot #Práctica 3 - Programa que calcula el precio de una compra con iva print ("Este programa calcula el IVA de un producto \n") producto = str(input("¿Qué producto ha adquirido? \n")) IVA = int(input("¿Cuál es el tipo de IVA del producto? \n")) bimponible = float(input ("¿Cuál es la base imponible del producto adquirido? \n")) pvp = ((IVA/100)+1)*bimponible print ("\n Su %s con tipo de IVA del %d y con base imponible %f tiene un precio de venta al público de %f €" % (producto,IVA,bimponible,pvp))
#Andreu Pomar Cabot #Práctica 5 - Determinadora de primos num = int (input ("Introduzca un número: ")) primo = True for i in range(2,num): if num%i==0: primo = False if primo == True: print ("Es primo") else: print ("No es primo")
#Andreu Pomar Cabot #Práctica 3 - Programa que calcula la media print ("Este programa calcula la media de tres notas \n") n1, n2, n3 = list(map(float, input ("Introduzca las tres notas cuya media quiera calcular (separadas por un espacio) \n").split())) media = (n1+n2+n3)/3 print ("La media de ",n1," ",n2," y ",n3," es", media) input ("Presione enter para cerrar el programa")
#Andreu Pomar Cabot #Ejercicio 6 - Hacer un programa que pide números incrementales y los guarda en una lista print("Este programa pide números incrementales y los guarda en una lista") entrada = int (input ("Escriba un numero: ")) ultimo = entrada-1 lista = [] while entrada > ultimo: lista.append (entrada) ultimo = entrada entrada = int (input ("Escriba otro número, mayor que %d: " % (ultimo))) print ("Los números son:",end=" ") for i in lista: print (i,end=", ") input()
import time import matplotlib.pyplot as plt import numpy as np import random def ChangeMaking(d, S, coins, used): for s in range(S + 1): count = s newCoin = 1 for j in [c for c in d if c <= s]: if coins[s-j] + 1 < count: count = coins[s-j] + 1 newCoin = j coins[s] = count used[s] = newCoin return coins # import timeit # d = [1, 2, 5, 10] # S = 57 # coins = [0]*(S + 1) # used = [0]*(S + 1) # print("Bảng quy đổi coins của giá trị", S) # start = timeit.default_timer() # print(ChangeMaking(d, S, coins, used)) # end = timeit.default_timer() # res = end - start # print("Thời gian chạy thuật toán Change-Making:", res) def Test(): d=[1, 2, 5, 10, 20, 50, 100] A=[] T=[] for i in range(100): S = random.randint(100 ,10000) A.append(S) coins= [0]*(S + 1) used = [0]*(S + 1) start=time.time() ChangeMaking(d, S, coins, used) T.append(time.time()-start) plt.plot(A, T,"-o") plt.xlabel('List Change Amount') plt.ylabel('List Time') plt.title('ChangeMaking') plt.show() Test()
acceleration = 9.8 on = True def distance_traveled(distance): if(distance > 100): print("distance traveled = ", distance, "\nGood going") elif(distance < 50): print("distance traveled = ", distance, "\nPathetic") else: print("distance traveled = ", distance, "\nnot bad") while(on): initialSpeed = float(input("Enter initial speed ")) time =float(input("Enter time of flight ")) distance_traveled(distance = (initialSpeed * time) + (0.5 * (acceleration * (time * time)))) decision = input("Another distance calculate? y/n ") if(decision == "n"): on = False
"""Plotting functions.""" import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import cm from scipy.optimize import OptimizeResult def plot_convergence(*args, **kwargs): """Plot one or several convergence traces. Parameters ---------- * `args[i]` [`OptimizeResult`, list of `OptimizeResult`, or tuple]: The result(s) for which to plot the convergence trace. - if `OptimizeResult`, then draw the corresponding single trace; - if list of `OptimizeResult`, then draw the corresponding convergence traces in transparency, along with the average convergence trace; - if tuple, then `args[i][0]` should be a string label and `args[i][1]` an `OptimizeResult` or a list of `OptimizeResult`. * `ax` [`Axes`, optional]: The matplotlib axes on which to draw the plot, or `None` to create a new one. * `true_minimum` [float, optional]: The true minimum value of the function, if known. * `yscale` [None or string, optional]: The scale for the y-axis. Returns ------- * `ax`: [`Axes`]: The matplotlib axes. """ # <3 legacy python ax = kwargs.get("ax", None) true_minimum = kwargs.get("true_minimum", None) yscale = kwargs.get("yscale", None) if ax is None: ax = plt.gca() ax.set_title("Convergence plot") ax.set_xlabel("Number of calls $n$") ax.set_ylabel(r"$\min f(x)$ after $n$ calls") ax.grid() if yscale is not None: ax.set_yscale(yscale) colors = cm.viridis(np.linspace(0.25, 1.0, len(args))) for results, color in zip(args, colors): if isinstance(results, tuple): name, results = results else: name = None if isinstance(results, OptimizeResult): n_calls = len(results.x_iters) mins = [np.min(results.func_vals[:i]) for i in range(1, n_calls + 1)] ax.plot(range(n_calls), mins, c=color, marker=".", markersize=12, lw=2, label=name) elif isinstance(results, list): n_calls = len(results[0].x_iters) mins = [[np.min(r.func_vals[:i]) for i in range(1, n_calls + 1)] for r in results] for m in mins: ax.plot(range(n_calls), m, c=color, alpha=0.2) ax.plot(range(n_calls), np.mean(mins, axis=0), c=color, marker=".", markersize=12, lw=2, label=name) if true_minimum: ax.axhline(true_minimum, linestyle="--", color="r", lw=1, label="True minimum") if true_minimum or name: ax.legend(loc="best") return ax
from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: answer = 0 if root is None : return answer queue = deque([root]) while queue : answer += 1 for _ in range(len(queue)) : now_node = queue.popleft() if now_node.left : queue.append(now_node.left) elif now_node.right : queue.append(now_node.right) return answer if __name__ == '__main__' : # arr_1 = [3, 9, 20, None, None, 15, 7] # arr_2 = [1, None, 2] # arr_3 = [] # arr_4 = [0] # # Sol = Solution() # print(Sol.maxDepth(arr_1)) root = TreeNode() print(root.val) print(root.left) print(root.right)
# -*- coding:utf-8 -*- import math numbers = list(map(float, input().split(" "))) numbers.sort(reverse=True) a,b,c = numbers if a >= (b + c): print('NAO FORMA TRIANGULO') else: if (a ** 2) == (b ** 2) + (c ** 2): print('TRIANGULO RETANGULO') if (a ** 2) > (b ** 2) + (c ** 2): print('TRIANGULO OBTUSANGULO') if (a ** 2) < (b ** 2) + (c ** 2): print('TRIANGULO ACUTANGULO') if a == b == c: print('TRIANGULO EQUILATERO') if numbers.count(a) == 2 or numbers.count(b) == 2: print('TRIANGULO ISOSCELES')
# -*- coding: utf-8 -*- valorSegundos = int(input()) hours = int(valorSegundos / 3600) minutes = int((valorSegundos % 3600) / 60) seconds = int((valorSegundos % 3600) % 60) print('%d:%d:%d' % (hours, minutes, seconds))
# -*- coding: utf-8 -*- originalNumbers = list(map(int, input().split(" "))) newNumbers = originalNumbers.copy() newNumbers.sort() for x in newNumbers: print(x) print() for x in originalNumbers: print(x)
# -*- coding:utf-8 -*- ddds = { 61:'Brasilia', 71:'Salvador', 11:'Sao Paulo', 21:'Rio de Janeiro', 32:'Juiz de Fora', 19:'Campinas', 27:'Vitoria', 31:'Belo Horizonte' } value = int(input()) if value in ddds: print(ddds[value]) else: print('DDD nao cadastrado')
print('1. feladat:') # keszits programot ami egy neveket tartalmazó listában # megmondja hogy van e benne Pista es kiirja azt is hogy hanyadik elem # a listában a Pista x = ['Eszti', 'Patrik', 'Tamás', 'Brigi', 'Pista', 'Anna', 'Márk'] print('Pista' in x) print('A listában a Pista a {}. név.'.format(x.index('Pista'))) print('2. feladat:') # keszits programot ami egy szamokat tartalmazo tomb-on vegig megy # es egy osszeg valtozoba bepakolja a szamok osszegét. A ciklus után az osszeg # valtozot irja ki a kepernyore y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] z = 0 for i in y: z += i print(z) print('3. feladat:') # Az elozo programot bovitsd ki úgy hogy uzenetet dobjon ha a tomb # egyik eleme # nem szam, es azt ne vegye figyelembe, de igy is osszegezze a többi number # tipusu elemeket, es irja ki az eredmenyt y = [1, 2, 3, 4, 5, 6, True, 7, 8, 9, 10] z = 0 for i in y: if type(i) == int: z += i if type(i) != int: print('A lista ezen eleme nem szám: {}'.format(i)) print(z) print('4. feladat:') # Az elozo programot bovitsd ki ugy hogy amennyiben nem szam a tomb # egyik eleme # akkor probalja meg a program a int fgv-el atkonvertalni # számmá, és ezután # újra nézze meg hogy szám e az adott elem. Ha igen, adja hozzá, # ha nem, jelezze # egy print-el hogy nem sikerult a konvertalas annál az elemnél y = [1, 2, 3, '4', 5, 6, 7, 8, 9, 10] z = 0 for i in y: if type(i) == int: z += i if type(i) != int: z = z + int(i) print(z) ''' Rájöttem, hogy az if, else, elif és return használata nekem még nagyon nehezen megy. Pl. mikor érdemes simán print-elni az 'ez nem szám' és hasonló üzeneteket, és mikor használjuk a returnt? Ha ilyen programokat próbálok írni, sokszor kapok SyntaxErrort. Szívesen gyakorolnék még ilyen feladatokat az órán, főleg ha ez a többikenek is segítene. Köszönettel, Nóra '''
print("Olá! para calcular seu IMC, insira os seguintes dados abaixo") peso = input("Digite seu peso: ") altura = input("Digite sua altura: ") IMC = float(peso) / float(altura) ** 2 print("O seu IMC é de:" ,IMC)
class Atm(object): def __init__(self,cardNumber, pinNumber, balanceAmount): self.cardNumber=cardNumber self.pinNumber=pinNumber self.balanceAmount=balanceAmount def CashWithdrawl(self, amount): self.amount=amount print(amount, "has been withdrawn from your account.") def BalanceEnquiry(self, amount, balanceAmount): amountLeft= self.balanceAmount-self.amount print(amountLeft, "is left in your account.") john=Atm(12345, 1004, 30000) john.CashWithdrawl(10000) john.BalanceEnquiry(10000, 30000)
# -*- coding: utf-8 -*- """ Created on Tue Jul 9 18:29:53 2019 @author: user """ #258. Add Digits class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ #input: 1~9 -> only one digit #output: 1~9 #input 10~.... -> internal add #output: 1,2,3,4,5,6,7,8,9,1(19),2(20),...,9,1,.... #intput 38 #(38-1) mod 9 = 37 mod 9 = 1 + 1 = 2 if num<=0: return 0 else: result=(num-1)%9+1 return result
# Project Euler Problem 25 # Problem Brief: # Determine which term in Fibonacci sequence is # the first to have 1000 digits # Source: # Brian Puthuff # 2015.04.01 # function to get next fibonacci number def next_fib(a = [], f_one = [], f_two = []): carry, sum = 0, 0 for i in range(999, -1, -1): sum = f_one[i] + f_two[i] + carry carry = 0 if(sum > 9): carry = 1 sum = sum % 10 a[i] = sum for i in range(999, -1, -1): f_one[i], f_two[i] = f_two[i], a[i] # main sequence # create lists next_term = [] fib_term1 = [] fib_term2 = [] # term count variable term = 3 # initialize lists for i in range(0, 1000, 1): next_term.append(0) fib_term1.append(0) fib_term2.append(0) # starting term fib_term1[999], fib_term2[999] = 1, 2 while(next_term[0] == 0): next_fib(next_term, fib_term1, fib_term2) term = term + 1 # print term print('\n') print("Term: %s" %term) # print 1000 digit number (for fun) print("The %s term in the Fibonacci sequence is:" %term) for i in next_term: print(i, end = '') print('\n')
class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if not A: return [[]] aRow = len(A) aCol = len(A[0]) bCol = len(B[0]) res = [[0 for _ in range(bCol)] for _ in range(aRow)] bMap = {} for row in range(aCol): bMap[row] = {} for col in range(bCol): if B[row][col]: bMap[row][col] = B[row][col] for arow in range(aRow): for acol in range(aCol): if A[arow][acol]: for bcol in bMap[acol]: res[arow][bcol] += A[arow][acol] * bMap[acol][bcol] return res # hashmap Solution O(n**2) class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ # corner case if len(A) == 0 or len(B) == 0 or len(A[0]) != len(B): return -1 # error m = len(A) n = len(B[0]) output = [[0 for _ in range(n)] for _ in range(m)] hashmap = dict() for i in range(len(A)): for j in range(len(A[0])): if A[i][j] != 0: tmp = hashmap.get(j, list()) tmp.append((i, A[i][j])) hashmap[j] = tmp for i in range(len(B)): for j in range(len(B[0])): if B[i][j] != 0: if i in hashmap: for ele in hashmap[i]: output[ele[0]][j] += ele[1] * B[i][j] return output # brute force solution AC class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if len(A) == 0 or len(A[0]) == 0 or len(B) == 0 or len(B[0]) == 0: return False if len(A[0]) != len(B): return False matrix = [[0 for _ in range(len(B[0]))] for _ in range(len(A))] for x in range(len(A)): for y in range(len(B[0])): value = 0 for z in range(len(B)): value += A[x][z] * B[z][y] matrix[x][y] = value return matrix
class PowerSet: def __init__(self): self.line = 20000 self.step = 3 self.slots = [None] * self.line # создает массив с size количеством слотов def size(self): count = 0 for i in self.slots: if i != None: count += 1 return count # количество элементов в множестве def hash_fun(self, value): # в качестве value поступают строки! hash = sum(map(ord, value)) % self.line # всегда возвращает корректный индекс слота return hash # суммируем значения кодов символов строки, и потом их брать по модулю размера таблицы. def put(self, value): num = self.hash_fun(value) count = 0 if value in self.slots: # если значение уже есть во множестве return else: while None in self.slots: if self.slots[num] == None: self.slots[num] = value return if self.slots[num] != None: num += self.step if num > self.line - 1: # находит индекс пустого слота для значения, или None num = count count += 1 return None def get(self, value): if value in self.slots: return True # возвращает True если value имеется в множестве, else: # иначе False return False def remove(self, value): if self.get(value) == True: num = self.hash_fun(value) # возвращает True если value удалено self.slots[num] = None return True else: # иначе False return False def intersection(self, set2): inter_set = [] for i in self.slots: if i in set2: # пересечение текущего множества и set2 inter_set.append(i) end_set = set(inter_set) return end_set def union(self, set2): for i in set2: if i in self.slots: # объединение текущего множества и set2 continue else: self.put(i) return self.slots def difference(self, set2): inter_set = [] for i in self.slots: if i not in set2 and i != None: # пересечение текущего множества и set2 inter_set.append(i) end_set = set(inter_set) return end_set # разница текущего множества и set2 def issubset(self, set2): count = 0 for i in set2: if i in self.slots and i != None: count += 1 if count == len(set2): return True else: return False
class Node: def __init__(self, v, d=None): self.value = v self.next = d class LinkedList: def __init__(self): self.head = None self.tail = None def add_in_tail(self, item): if self.head == None: self.head = item else: self.tail.next = item self.tail = item def print_all_nodes(self): node = self.head while node != None: print(node.value) node = node.next def find(self, val): node = self.head while node != None: if node.value == val: return node else: node = node.next return None def len(self): node = self.head count = 0 while node != None: count += 1 node = node.next return count def clean(self): self.head = None self.tail = None # проверить если элемента нет в списке def delete(self, val, all=False): # если нужно найти на удаление более 2 х элементов мб if self.head == None: # после нахождения 1 го запускать цикл по новой return one_run = self.head two_run = self.head if one_run.value == val and self.head.next == None: # если удаляем один элемент self.head = self.tail = None return if one_run.value == val: # если удаляем первый элемент self.head = self.head.next while one_run != None: if one_run.value == val: two_run.next = one_run.next if one_run == self.tail: self.tail = two_run if all == False: return else: one_run = self.head two_run = self.head else: two_run = one_run one_run = one_run.next def find_all(self, val): node = self.head arr = [] while node != None: if node.value == val: arr.append(node) node = node.next else: node = node.next return arr def insert(self, afterNode, newNode):# на вход подаются ноды my_list.insert(None, Node(63)) node = self.head end = self.tail if self.head == None: self.tail = self.head = newNode # self.tail = self.head = Node(newNode) return while node != None: if node.value == end.value: # вставляем ноду в конец списка node.next = newNode #node.next = newNode(node.next) self.tail = self.tail.next return if node.value == afterNode.value: # вставляем ноду в начало node.next = Node(newNode.value, node.next) # node.next = newNode(node.next) return else: node = node.next #
class Queue: def __init__(self): self.queue_1 = [] self.queue_2 = [] def enqueue(self, item): return self.queue_1.append(item) def copy(self): self.queue_2.append(self.queue_1[-1]) self.queue_1.pop() def dequeue(self): if self.size_1() == self.size_2() == 0: return None # если очередь пустая if self.size_2() == 0: while self.size_1() != 0: self.copy() first_el = self.queue_2[-1] self.queue_2.pop() return first_el def size_1(self): return len(self.queue_1) def size_2(self): return len(self.queue_2) qu = Queue() qu.enqueue(1) qu.enqueue(2) qu.enqueue(3) qu.enqueue(4) qu.dequeue() qu.enqueue(5) print(qu.dequeue())
class BSTNode: def __init__(self, key, val, parent): self.NodeKey = key self.NodeValue = val self.Parent = parent self.LeftChild = None self.RightChild = None class BSTFind: def __init__(self): self.Node = None # None если # в дереве вообще нету узлов self.NodeHasKey = False # True если узел найден self.ToLeft = False # True, если родительскому узлу надо # добавить новый узел левым потомком class BST: def __init__(self, node): self.Root = node def FindNodeByKey(self, key): cursor_node = self.Root BSTFind.NodeHasKey = False if cursor_node == None: BSTFind.Node = None return BSTFind while True: if cursor_node.NodeKey == key: BSTFind.NodeHasKey = True BSTFind.Node = cursor_node return BSTFind if cursor_node.NodeKey < key and cursor_node.RightChild != None: cursor_node = cursor_node.RightChild BSTFind.Node = cursor_node if cursor_node.NodeKey < key and cursor_node.RightChild == None: BSTFind.Node = cursor_node BSTFind.ToLeft = False return BSTFind if cursor_node.NodeKey > key and cursor_node.LeftChild != None: cursor_node = cursor_node.LeftChild BSTFind.Node = cursor_node if cursor_node.NodeKey > key and cursor_node.LeftChild == None: BSTFind.Node = cursor_node BSTFind.ToLeft = True return BSTFind def AddKeyValue(self, key, val): self.FindNodeByKey(key) if BSTFind.Node == None or BSTFind.NodeHasKey == True: return False if BSTFind.ToLeft == False: node = BSTNode(key, val, BSTFind.Node) BSTFind.Node.RightChild = node return True if BSTFind.ToLeft == True: node = BSTNode(key, val, BSTFind.Node) BSTFind.Node.LeftChild = node return True def FinMinMax(self, FromNode, FindMax): cursor_node = self.Root if cursor_node == None: return None cursor_node = FromNode if cursor_node == None: return None if cursor_node.RightChild == None and cursor_node.LeftChild == None: return None if FindMax == True: while cursor_node.RightChild != None: cursor_node = cursor_node.RightChild if cursor_node.RightChild == None: return cursor_node if FindMax == False: while cursor_node.LeftChild != None: cursor_node = cursor_node.LeftChild if cursor_node.LeftChild == None: return cursor_node def DeleteNodeByKey(self, key): self.FindNodeByKey(key) del_node = BSTFind.Node if BSTFind.NodeHasKey == False: return False if del_node.LeftChild == None and del_node.RightChild == None and del_node.Parent == None: self.Root = None BSTFind.Node = None return True if del_node.LeftChild == None and del_node.RightChild == None and del_node.Parent.RightChild == del_node: del_node.Parent.RightChild = None del_node.Parent = None BSTFind.Node = None return True if del_node.LeftChild == None and del_node.RightChild == None and del_node.Parent.LeftChild == del_node: del_node.Parent.LeftChild = None del_node.Parent = None BSTFind.Node = None return True if del_node.LeftChild != None and del_node.RightChild == None: del_node.LeftChild.Parent = del_node.Parent if del_node.Parent.LeftChild == del_node: del_node.Parent.LeftChild = del_node.LeftChild BSTFind.Node = None return True if del_node.Parent.RightChild == del_node: del_node.Parent.RightChild = del_node.LeftChild BSTFind.Node = None return True if del_node.LeftChild == None and del_node.RightChild != None: del_node.RightChild.Parent = del_node.Parent if del_node.Parent.LeftChild == del_node: del_node.Parent.LeftChild = del_node.RightChild BSTFind.Node = None return True if del_node.Parent.RightChild == del_node: del_node.Parent.RightChild = del_node.RightChild BSTFind.Node = None return True if del_node.LeftChild != None and del_node.RightChild != None: if del_node.LeftChild.LeftChild == None and del_node.RightChild.RightChild == None and del_node.LeftChild.RightChild == None and del_node.RightChild.LeftChild == None: if del_node.Parent.LeftChild == del_node: del_node.RightChild.Parent = del_node.Parent del_node.Parent.LeftChild = del_node.RightChild del_node.LeftChild.Parent = del_node.RightChild del_node.RightChild.LeftChild = del_node.LeftChild BSTFind.Node = None return True if del_node.Parent.RightChild == del_node: # редактировать del_node.RightChild.Parent = del_node.Parent del_node.Parent.RightChild = del_node.RightChild del_node.LeftChild.Parent = del_node.RightChild del_node.RightChild.LeftChild = del_node.LeftChild BSTFind.Node = None return True stop_node = del_node del_node = del_node.RightChild while True: if del_node.LeftChild == None and del_node.RightChild == None: if stop_node.Parent.LeftChild == stop_node: stop_node.LeftChild.Parent = del_node del_node.Parent.LeftChild = None del_node.Parent = stop_node.Parent stop_node.Parent.LeftChild = del_node del_node.RightChild = stop_node.RightChild stop_node.RightChild.Parent = del_node del_node.LeftChild = stop_node.LeftChild BSTFind.Node = None return True if stop_node.Parent.RightChild == stop_node: stop_node.LeftChild.Parent = del_node del_node.Parent.LeftChild = None del_node.Parent = stop_node.Parent stop_node.Parent.RightChild = del_node del_node.RightChild = stop_node.RightChild stop_node.RightChild.Parent = del_node del_node.LeftChild = stop_node.LeftChild BSTFind.Node = None return True if del_node.LeftChild == None and del_node.RightChild != None: stop_node.LeftChild.Parent = del_node del_node.Parent = stop_node.Parent stop_node.Parent.RightChild = del_node del_node.RightChild = stop_node.RightChild stop_node.RightChild.Parent = del_node del_node.LeftChild = stop_node.LeftChild BSTFind.Node = None return True else: del_node = del_node.LeftChild def Count(self): vizit = [] # надо предусмотреть если корень нана или только один корень stack = [] node = self.Root if node == None: return 0 vizit.append(node) if node.LeftChild != None: stack.append(node.LeftChild) if node.RightChild != None: stack.append(node.RightChild) if node.LeftChild == None and node.RightChild == None: return 1 while True: node = stack[0] if node.LeftChild != None: stack.append(node.LeftChild) if node.RightChild != None: stack.append(node.RightChild) vizit.append(node) stack.pop(0) if len(stack) == 0: break return len(vizit)
class Node: def __init__(self, v): self.value = v self.prev = None self.next = None class OrderedList: def __init__(self, asc): self.head = None self.tail = None self.__ascending = asc def compare(self, v1, v2): if v1 < v2: return -1 if v1 == v2: return 0 if v1 > v2: return 1 # -1 если v1 < v2 # 0 если v1 == v2 # +1 если v1 > v2 def add(self, value): node = self.head node_end = self.tail if self.head == None: # вставляем элемент если список пустой self.tail = self.head = Node(value) return if self.head == self.tail: # проверяем что элемент один if self.compare(node.value, value) == -1 or self.compare(node.value, value) == 0: if self.__ascending == True: node.next = Node(value) # вставляем элемент назад в списке 1 элемент и спис возраст node.next.prev = node self.tail = node.next return if self.__ascending == False: # вставляем элемент назад в списке 1 элемент и спис увывание node.prev = Node(value) node.prev.next = node self.head = node.prev return if self.compare(node.value, value) == 1: # вставляем элемент вперед в списке 1 элемент и спис возраст if self.__ascending == True: node.prev = Node(value) node.prev.next = node self.head = node.prev return if self.__ascending == False: node.next = Node(value) # вставляем элемент назад в списке 1 элемент и спис убывание node.next.prev = node self.tail = node.next return if self.head != self.tail: # вставляем по концам self.head != self.tail больше 1 эл в списк if self.__ascending == True: if self.compare(node_end.value, value) == -1 or self.compare(node_end.value, value) == 0: node_end.next = Node(value) # вставляем элемент в хвост, в списке <1 элемент и спис возраст node.next.prev = node self.tail = node.next self.tail = node_end.next node_end.next.prev = node_end return if self.compare(node.value, value) == 1 or self.compare(node.value, value) == 0: node.prev = Node(value) # вставляем элемент в голову в списке <1 элемент и спис возраст node.prev.next = node self.head = node.prev return if self.__ascending == False: if self.compare(node_end.value, value) == 1 or self.compare(node_end.value, value) == 0: node_end.next = Node(value) # вставляем элемент в хвост, в списке <1 элемент и спис убывание node.next.prev = node self.tail = node.next self.tail = node_end.next node_end.next.prev = node_end return if self.compare(node.value, value) == -1 or self.compare(node.value, value) == 0: node.prev = Node(value) # вставляем элемент в голову в списке <1 элемент и спис убывание node.prev.next = node self.head = node.prev return while node is not None: # вставляем элемент назад в списке <1 элемент м/у 2 мя элементамии и спис возраст if (self.compare(node.value, value) == -1 and self.compare(node.next.value, value) == 1) or ( self.compare(node.value, value) == 1 and self.compare(node.next.value, value) == -1): node_next = node.next node.next = Node(value) node.next.prev = node node_next.prev = node.next node.next.next = node_next return else: node = node.next def find(self, val): return None # здесь будет ваш код def delete(self, val): pass # здесь будет ваш код def clean(self, asc): self.__ascending = asc pass # здесь будет ваш код def len(self): node = self.head court = 0 while node is not None: court += 1 node = node.next return court # здесь будет ваш код def get_all(self): r = [] node = self.head while node != None: r.append(node.value) node = node.next return r my_list = OrderedList(False) my_list.add(6) my_list.add(5) my_list.add(8) my_list.add(7) my_list.add(5) print(my_list.get_all())
def calc_volume(temp): if(temp.isnumeric()==False): raise ValueError("The length must be a positive integer") num = int(temp) return num*num*num #print(calc_volume("4"));
my_set = {1, 5, 7, 3, 8, 2} print(my_set) my_bitch = set ([1, 4, 6]) print(my_bitch) my_set.add(4) print(my_set) my_set.update([6, 9]) print(my_set) my_set.discard(3) print(my_set) my_set.remove(7) print(my_set) my_set.discard(7) print(my_set) returned_value = my_set.pop() print(my_set) print(returned_value) A = {'a', 'e', 'y', 'z', 'm'} B = {'x', 'p', 'g', 'a', 'y'} result = A | B print(result) result = B.union(A) print(result) intercars = A & B print(intercars) intercars = B.intersection(A) diff = A - B print(diff) diff = B - A print(diff) diff = A.difference(B) print(diff) sdiff = A ^ B print(sdiff) sdiff = A.symmetric_difference(B) print(sdiff) for letters in my_set: print(letters) my_dict = {1: 'apple', 2: 'ball'} my_dick = dict({1:'apple', 2: 'ball'}) print(my_dick) dick_name = my_dick[1] print(dick_name) dick_name = my_dick.get(1) my_dick['fruit'] = 'peack' my_dick[2] = "banana" print(my_dick) value = my_dick.pop(1) del my_dict[1] print(my_dict) print(1 in my_dick) print("sperms" in my_dict)
"""# Outer enclosing function def print_msg(msg): # This is a nested function def printer(): print(msg) #calling printer() from inside print_msg() printer() print_msg("HELlo") #Define a closure # Outer enclosing function def print_msg(msg): def printer(): print(msg) return printer # returning printer() # Now let's try calling this function another = print_msg("HELlo") another()""" def make_multiplier_of(n): def multiplier(x): return x * n return multiplier times3 = make_multiplier_of(3) times7 = make_multiplier_of(7) print(times3(9)) print(times7(3)) print(times7(times3(2)))
class Polygon: def _init_(self, no_of_sides): self.n = no_of_sides self.sides = [] for i in range(no_of_sides): self.sides.append(0) def input_sides(self): for i in range(self.n): self.side[i] = float(input("Enter side"+str(i+1)+" : ")) def display_sides(self): for i in range(self.n): print("sides", i+1, "is", self.sides[i]) p1 = Polygon(3) p1.input_sides() p1.display_sides()
class Number: def add(self, a, b): return a+b def multiply(self, a, b): return a*b #instantiate an object n1 = Number() sum = n1.add(2, 5) print(sum) product = n1.multiply(2, 5) print(product)
#파이썬 자료구조 #리스트:sequence 자료구조를 사용 #sequence:순서가 있는 데이터 구조를 의미 #리스트,튜플,레인지,문자열등이 sequence 구조 사용 #리스트는 []을 이용해서 각 요소에 접근할 수 있다 msg = 'Hello,World!' #파이썬에서는 자료구조를 의미하는 접미사를 #변수명에 사용하기도 한다 list1_list = [] #빈 리스트 list2_list = [1,2,3,4,5] #숫자 list3_list = ['a','b','c'] #문자 list4_list = ['a','b','c',1,2,3,True] #혼합 print(list1_list) #간단한 연산 #요소 존재 여부 파악 : in/not in 연산자 print(1 in list1_list) print('a' in list1_list) print(3 in list2_list) #길이 연산 : len() print(len(list1_list)) print(len(list2_list)) #연결 연산 + print(list2_list+list3_list) #반복 연산 * print(list2_list*2) #요소의 특정값 참조 : index 사용 print(msg[5],msg[8]) print(list2_list[2]) #요소값 변경 : index,=사용 list2_list[2]=-3 print(list2_list) #주민코드에서 성별 여부 jumin=[1,2,3,4,5,6,2,2,3,4,5,6,7] if jumin[6] == 1: print("남자") else: print("여자") #주민코드에서 생년월일 추출 for i in range(0,6): print(jumin[i],end=' ') #줄바꿈없이 출력시 종결문자를 지정 #특정범위내 요소들을 추출할때는 슬라이스 사용[i:j:step] print(jumin[0:6]) #생년월일 print(jumin[:6]) print(jumin[6:]) #생년월일 제외 나머지부분 print(jumin[:]) #모두 print(jumin[0:6:2]) #홀수자리만 추출 print(jumin[::-1]) #역순 출력 #print(jumin[100]) #인덱스 초과 - 오류? print(jumin[0:100:2]) #인덱스 초과 - 오류? #리스트관련 통계함수 print(sum(list2_list)) print(min(list2_list)) print(max(list2_list)) #리스트가 주어지면 이것의 가운데있는 요소값을 출력 #[1,2,6,8,4] = 6 #[1,2,6,8,4,10]= 6,8 list=[1,2,3,4,5,6] size=len(list) mid=int(size/2) print('가운데값:',list[mid]) #항목갯수가 홀수일때 print('가운데값:',list[mid-1:mid+1]) #항목갯수가 짝수일때 def listcenter(list): size = len(list) mid = int(size/2) if size %2 ==0: #짝수인경우 print(list[mid-1:mid+1]) else: print(list[mid]) listcenter([1,2,3]) listcenter([1, 2, 3,4]) #리스트 조작 함수 #요소 추가 : append list = [1,2,3,4,5] list.append(9) list.append(7) print(list) #요소 추가 : insert(위치, 값) list.insert(6,8) print(list) #요소 제거 : remove(값) list.remove(9) print(list) #요소제거 : pop(), pop(위치) list.pop(5) print(list) list.pop() print(list) #모두제거 : clear() list.clear() print(list)
import tkinter as tk import time root = tk.Tk() root.geometry('400x400') root.title('canvasの使い方') #図形を壁画するキャンバスをウインド上に作成 canvas=tk.Canvas(root,width=300,height=300,bg="white") canvas.pack() #図形の壁画 dx=20 dy=20 square=canvas.create_rectangle(5,5,5+dx,5+dy,fill='red')#四角 x=150#四角の初期x座標 y=150#四角の初期y座標 while True: # Coords そのアイテムIDの図形を指定した文だけ変形をしていく。 # ID、左上のX座標、左上のY座標、右下のx座標、右下のy座標 canvas.coords(square,x,y,x+dx,y+dy) y += 1 time.sleep(0.02) #0.02秒ずつ更新 root.update() #ウインド画面を更新 root.mainloop()
import difflib # Rentrer le non des deux fichiers newFile = input("Enter the new filename: ") oldFile = input("Enter the old filename: ") # Print confirmation print("-----------------------------------") print("Comapraison des fichiers ", " > " + newFile, " < " +oldFile, sep = '\n') print("-----------------------------------") #ouverture des deux fichiers fnewLine = open(newFile).readlines() foldLine = open(oldFile).readlines() fichier = open('conffinal.txt','w') #faire la différence entre les deux fichiers et mettre la différence dans un fichier html diff = difflib.HtmlDiff().make_file(fnewLine, foldLine, newFile, oldFile) difference_report = open('different_report.html','w') difference_report.write(diff) print("- Prenez le fichier different_report.html que vous avez vu apparaitre.") print("- Ouvrez ce fichier sur un navigateur web.") difference_report.close() #ouverture des deux fichiers f1 = open(newFile,'r') f2 = open(oldFile,'r') # lecture de la premiére ligne du fichier f1_line = f1.readline() f2_line = f2.readline() # Initialisation d'un compteur li = 1 li2 =1 difference = False # Boucle permettant de comparer les deux fichiers ligne par ligne while f1_line != '' or f2_line != '': # enlever les espaces au debut et à la fin de chaque ligne f1_line = f1_line.rstrip() f2_line = f2_line.rstrip() if f1_line == '' and f2_line != '': difference = True fichier.write(f2_line + '\n') elif f1_line != f2_line : fichier.write(f1_line + '\n') difference = True else: fichier.write(f1_line + '\n') #lit la ligne suivante des fichiers f1_line = f1.readline() f2_line = f2.readline() #increment le compteur de ligne li += 1 li2 += 1 #premet d'indiquer qu'une différence est présent if difference == True: print("-----------------------------------") print("- différences detectées, vous pouvez consulter le fichier : different_report.html" ) else: print("-----------------------------------") print("Les fichiers sont identiques") # fermeture des fichiers fichier.close() f1.close() f2.close()
class Description(): """Given a list of non negative integers, arrange them in such a manner that they form the largest number possible. The result is going to be very large, hence return the result in the form of a string. Input: The first line of input consists number of the test cases. The description of T test cases is as follows: The first line of each test case contains the size of the array, and the second line has the elements of the array. Output: In each separate line print the largest number formed by arranging the elements of the array in the form of a string. Constraints: 1 ≤ T ≤ 70 1 ≤ N ≤ 100 0 ≤ A[i] ≤ 1000 """ def merge_sort(a_list): if len(a_list) > 1: mid = len(a_list)//2 #import pdb; pdb.set_trace() left_list = a_list[:mid] right_list = a_list[mid:] merge_sort(left_list) merge_sort(right_list) i, j, k = (0,)*3 while i < len(left_list) and j < len(right_list): if compare(left_list[i],right_list[j]): a_list[k] = left_list[i] i += 1 k += 1 else: a_list[k] = right_list[j] j += 1 k += 1 while i < len(left_list): a_list[k] = left_list[i] i += 1 k += 1 while j < len(right_list): a_list[k] = right_list[j] j += 1 k += 1 def compare(l_val, r_val): val1 = int(l_val + r_val) val2 = int(r_val + l_val) if val1 > val2: return True else: return False #li = [4, 7, 2, 1, 7, 9] #merge_sort(li) #print(li) test_cases = int(input()) for _ in range(test_cases): arr_len = int(input()) arr = input().split() merge_sort(arr) #print(arr) temp = '' for i in arr: temp += i print(temp)
income = float(input("Enter the annual income: ")) if income <= 556.02/.18: tax = 0 elif income <= 85528: tax = (income *.18) - 556.02 else: tax = 14839.02 + .32*(income-85528) tax = round(tax, 0) print("The tax is:", tax, "thalers")
from util import Stack, Queue from graph import Graph import random class User: def __init__(self, name): self.name = name class SocialGraph: def __init__(self): self.last_id = 0 self.users = {} self.friendships = {} def add_friendship(self, user_id, friend_id): """ Creates a bi-directional friendship """ if user_id == friend_id: print("WARNING: You cannot be friends with yourself") elif friend_id in self.friendships[user_id] or user_id in self.friendships[friend_id]: print("WARNING: Friendship already exists") else: self.friendships[user_id].add(friend_id) self.friendships[friend_id].add(user_id) def add_user(self, name): """ Create a new user with a sequential integer ID """ self.last_id += 1 # automatically increment the ID to assign the new user self.users[self.last_id] = User(name) self.friendships[self.last_id] = set() def populate_graph(self, num_users, avg_friendships): """ Takes a number of users and an average number of friendships as arguments Creates that number of users and a randomly distributed friendships between those users. The number of users must be greater than the average number of friendships. """ # Reset graph self.last_id = 0 self.users = {} self.friendships = {} # !!!! IMPLEMENT ME # Add users for i in range(0, num_users): self.add_user(f"User {i}") # Create friendships # Generate all possible friendship combinations possible_friendships = [] # Avoid duplicates by ensuring the first number # is smaller than the second for user_id in self.users: for friend_id in range(user_id + 1, self.last_id + 1): # print(range(user_id + 1, self.last_id + 1)) possible_friendships.append((user_id, friend_id)) # Shuffle the possible friendships random.shuffle(possible_friendships) # print('self.users:', random.shuffle(possible_friendships)) # Create friendships for the first X pairs of the list # X is determined by the formula: num_users * avg_friendships // 2 # Need to divide by 2 since each add_friendship() creates 2 friendships for i in range(num_users * avg_friendships // 2): friendship = possible_friendships[i] self.add_friendship(friendship[0], friendship[1]) def get_all_social_paths(self, user_id): """ Takes a user's user_id as an argument Returns a dictionary containing every user in that user's extended network with the shortest friendship path between them. The key is the friend's ID and the value is the path. """ q = Queue() starting_person = user_id q.enqueue([starting_person]) visited = {} # Note that this is a dictionary, not a set # Repeat until queue is empty while q.size() > 0: # Dequeue first person i.e: remove from queue person = q.dequeue() # This is my path # print('person:', person) # Grab the last person (vertex) from the path and set it to our current_person current_person = person[-1] # print('current:', current_person) # Have we visited the person yet? If not then visit it. if current_person not in visited: # print('visited:', visited) # Set currently visited person to the person position currently at visited[current_person] = person # For each friend of the starting_person... for friend in self.friendships[current_person]: # If the friend has not been visited yet... if friend not in visited: # Make a *copy* of person next_person = list(person) # Add current friend to next_person next_person.append(friend) # Make this friend the next starting_person q.enqueue(next_person) return visited if __name__ == '__main__': sg = SocialGraph() sg.populate_graph(10, 2) print('sg.friendships:', sg.friendships) connections = sg.get_all_social_paths(1) print('connections:', connections)
""" iterative binary search """ def binary_search(array, target): start = 0 end = len(array) while start <= end: mid = (start + end) // 2 if array[mid] == target: return mid if array[mid] > target: end = mid - 1 else: start = mid + 1 return None if __name__ == "__main__": target = int(input("input a target integer: ")) array = list(map(int, input("input integer values: ").strip().split())) array.sort() result = binary_search(array, target) print(result if result else "No such element in array")
def rec(d, n): if d == n: print("_" * 4 * d, end='') print("\"재귀함수가 뭔가요?\"") print("_" * 4 * d, end='') print("\"재귀함수는 자기 자신을 호출하는 함수라네\"") print("_" * 4 * d, end='') print("라고 답변하였지.") return print("_" * 4 * d, end='') print("\"재귀함수가 뭔가요?\"") print("_" * 4 * d, end='') print("\"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.") print("_" * 4 * d, end='') print("마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.") print("_" * 4 * d, end='') print("그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어.\"") rec(d + 1, n) print("_" * 4 * d, end='') print("라고 답변하였지.") if __name__ == "__main__": n = int(input()) print("어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다.") rec(0, n)