text
stringlengths
37
1.41M
#tabuada com for n = float(input('Digite um número: ')) print('Tabuada do número {}'.format(n)) for i in range (0, 11): print('{} x {} = {}'.format(i, n, i*n))
#soma de números pares com for soma = 0 cont = 0 for i in range(6): n = (int(input('digite o {}º número: '.format(i+1)))) if n % 2 == 0: soma += n cont += 1 print('A quantidade de números pares foi {} e sua é: {}'.format(cont, soma))
# lambda 활용법 ''' x = lambda a: a+10 print(x(5)) x = lambda a,b : a *b print(x(5,6)) def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11)) mytripler = myfunc(3) print(mytripler(11)) ''' def a(n): return lambda i: i*n mydoubler = a(2) print(mydoubler(11))
''' 생성자 (Constructor) 상속 : 일반화 **클래스를 상속하기 위해서는 다음처럼 클래스 이름 뒤 괄호 안에 상속할 클래스 이름을 넣어주면 된다. 형식 ] class 클래스 이름(상속할 클래스 이름) ''' class FourCal: def __init__(self,first,second): self.first = first self.second = second def sum(self,bbb): result = self.first + self.second return result class MoreFourCal(FourCal): def pow(self,aaa): result = aaa**2 return result a = MoreFourCal(4,2) print(a.pow(5)) print(a.sum()) a= MoreFourCal(2,7)
#튜플 요솟값을 삭제하려 할 때 t1 = (1,2,'a','b') print(t1[0]) #del t1[0] # 삭제시 error 발생 #t1[0]='c' #변경 시 error 발생 #인덱싱하기 t1 = (1,2,'a','b') print(t1[0]) print(t1[3]) #슬라이싱하기 print(t1[1:]) print("-"*20)
#a = [1,2,3,4] #result = [n + 2 for n in a if n % 2 == 1] # #print(result) #결과값에 2의 배수만 출력하시오 a = [6,8,12,33] result = [n*3 for n in a if n % 2 == 0] print(result)
#1~10 까지의 홀수합 출력!! odd=0 even=0 #for i in range(1,11,2): # odd = odd+i #print(odd) #다른방법으로 해보세요~! a = 0 b = 0 for i in range(1,11): if i % 2 == 1: a = a+i print("1~10까지의 홀수의 합은 : ",a) for j in range(1,11): if j % 2 == 0: b = b+j print("1~10까지의 짝수의 합은 : ",b)
a= ' hi ' print(a) print(a.lstrip()+'Chk') print(a.rstrip()+'Chk') print(a.strip()+'Chk') ##공백제거 print('-'*15) #문자열 바꾸기(replace) a='Life is too short' print(a) cng=a.replace('Life','Your leg') print(cng) print('-'*15)
menu = ['오렌지','딸기','복숭아','망고','포도','종료'] # 0 1 2 3 4 5 money = [1000,2500,1500,2000,2000] # 0 1 2 3 4 while True: print("="*50) print("*****홍익 대학교 과일 판매머신 V03 *****") print("="*50) for i in range(0,5): print (i+1,'번 ',menu[i] , ":" , money[i] , "원") print('6. 종료') print("="*50) n = input("%30s"%"구매번호를입력하세요.(1~6) : ") n= int(n) if n == 1: print (menu[n-1] , "는 " , money[n-1] , "원입니다.") elif n ==2: print (menu[n-1] , "는 " , money[n-1] , "원입니다.") elif n ==3: print (menu[n-1] , "는 " , money[n-1] , "원입니다.") elif n ==4: print (menu[n-1] , "는 " , money[n-1] , "원입니다.") elif n ==5: print (menu[n-1] , "는 " , money[n-1] , "원입니다.") elif n ==6: print ("또 오세요") break else: print("구매번호를 확인하세요") coin=int(input("%32s"%"금액을 투입하세요 : ")) print("%s%d 원 입니다"%("투입한 금액은",coin)) print("거스름돈은 %d"%(coin-money[n-1]))
# return문을 2번 사용하면, # 두 번째 return문인 return a*b는 실행되지 않는다 def add_and_mul(a, b): return a+b return a*b result = add_and_mul(2,3) print(result) print('-'*10) # [return의 또 다른 쓰임새] # return을 단독으로 써서 함수를 즉시 빠져나갈 수 있다 def say_nick(nick): if nick == "바보": return nick # print("나의 별명은 %s 입니다." %nick) say_nick('야호') say_nick('바보') print('-'*10)
import math as m; i=int(input("Enter a number to find factorial: ")) print("Factorial of {} = {}".format(i,m.factorial(i)))
from person import Person from metode import print_contacts from metode import add_contact from metode import edit_contact from metode import delte_contact def main(): print("Dobrodosli v programu Contact Book") john = Person(first_name="John", last_name="Clark", phone_number="89348239429", email="[email protected]", birth_date=1978) marissa = Person(first_name="Marissa", last_name="Mayer", phone_number="83483204032", email="[email protected]", birth_date=1975) bruce = Person(first_name="Bruce", last_name="Wayne", phone_number="902432309443", email="[email protected]", birth_date=1989) contacts = [john, marissa, bruce] while True: print "" print "Proim izberi eno od naslednjih moznosti:" print "a) Izpisi vse svoje stike" print "b) Dodaj nov stik" print "c) Uredi stik" print "d) Izbrisi stik" print "e) Izhod iz programa." print "" selection = raw_input("Vnesi svojo izbiro (a, b, c, d or e): ") print "" if selection.lower() == "a": print_contacts(contacts) elif selection.lower() == "b": add_contact(contacts) elif selection.lower() == "c": edit_contact(contacts) elif selection.lower() == "d": delte_contact(contacts) elif selection.lower() == "e": print "Hvala za uporabo programa! " break else: print "Ne razumem tvoje izbire. Prosim poskusi ponovno." continue if __name__ == "__main__": main()
import csv def insert_rec(data): with open('records.csv', 'a') as csvfile: fw = csv.writer(csvfile) fw.writerow(data) print('Record inserted') def display_rec(): try: with open('records.csv', 'r') as csvfile: fr = csv.reader(csvfile) for row in fr: print(row) except IOError: print('File not found:') def update_rec(rollno): try: data = [] total = [] with open('records.csv', 'r') as csvfile: fr = csv.reader(csvfile) total = list(fr) for row in total: if (row[1] == rollno): name = input('Name') branch = input('Branch') year = input('Year') cgpa = input('CGPA') data.append(name) data.append(rollno) data.append(branch) data.append(year) data.append(cgpa) with open('records.csv', 'a+') as csvfile: fw = csv.writer(csvfile) fw.writerows(total) except IOError: print('File not found:') while (1): char = input('Enter i to insert record, d to display records and u to update record(enter q to quit)') if (char == 'q'): break if (char == 'i'): print('Enter following details : ') name = input('Name') roll_no = input('Roll no') branch = input('Branch') year = input('Year') cgpa = input('CGPA') data = [] data.append(name) data.append(roll_no) data.append(branch) data.append(year) data.append(cgpa) insert_rec(data) if (char == 'd'): display_rec() if (char == 'u'): rollno = input('Enter roll number of student: ') update_rec(rollno) display_rec()
# consists of brackets containing an expression followed by # a for clause, then zero or more for or if clauses # result is a new list resulting from evaluating the in the context of the # for and if clauses which follow it. # squares / list comprehension example squares = [x**2 for x in range(10)] print(squares) # the 'list comprehension' # combine elements of two liss if they are not equal print([(x,y) for x in [1,2,3] for y in [3,1,4] if x != y])
# Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. # The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. # You must write an algorithm that runs in O(n) time and without using the division operation. class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: res = [1] * len(nums) # Start from left to right # Calculate the product of numbers before an index and store that value in res at that index prefix = 1 for i in range(len(nums)): res[i] = prefix prefix = prefix * nums[i] # Start from right to left # Calculate the product of numbers after an index and multiply it with existing value in res at that index # These 2 calculation will give the product of numbers before and after the index postfix = 1 for i in range(len(nums)-1,-1,-1): res[i] = postfix * res[i] postfix = postfix * nums[i] return res
# Given a string s, find the length of the longest substring without repeating characters. class Solution: def lengthOfLongestSubstring(self, s: str) -> int: # Maintain set of words encountered so far w = set() res = 0 l = 0 # Maintaining window of only unique elements and checking length in every iteration for r in range(len(s)): while(s[r] in w): w.remove(s[l]) l += 1 w.add(s[r]) res = max(res,len(w)) return res
# You are given an array prices where prices[i] is the price of a given stock on the ith day. # You want to maximize your profit by choosing a single day to buy one stock # and choosing a different day in the future to sell that stock. # Return the maximum profit you can achieve from this transaction. # If you cannot achieve any profit, return 0. class Solution: def maxProfit(self, prices: List[int]) -> int: # Handling edge case if(len(prices)<=1): return 0 maxProfit = 0 l = 0 r = 1 while r < len(prices): # if price of value of left right pointer is less than that at right we calculate profit # Else left pointer will move to position of right if(prices[l] < prices[r]): maxProfit = max(maxProfit,prices[r]-prices[l]) else : l = r # In both case right pointer will be increased by 1 r += 1 return maxProfit
#Given the root of a binary tree, return its maximum depth. # A binary tree's maximum depth is the number of nodes along the longest path from the root node # down to the farthest leaf node. class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: #print(root) stack = [] depth = 0 # Add Tree to stack if root is not None: stack.append((1,root)) while stack!=[]: # Get the last node in the stack current_depth, root = stack.pop() # If node is not none then add it's childern to the stack if root is not None: # If depth of current node is greater than previosuly encountered nodes # then depth is updated depth = max(depth,current_depth) # Adding left child to stack stack.append((current_depth+1,root.left)) # Adding right child to stack stack.append((current_depth+1,root.right)) return depth
# Given the root of a binary tree, return the length of the diameter of the tree. # The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. # The length of a path between two nodes is represented by the number of edges between them. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: res = 0 def dfs(node): if not node : return 0 lHeight = dfs(node.left) rheight = dfs(node.right) nonlocal res res = max(res,lHeight+rheight) # returning maximum of left and right child return 1 + max(lHeight, rheight) dfs(root) return res
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import xml.etree.ElementTree as ET import operator from collections import namedtuple from itertools import islice from math import sin, cos, atan2, radians, sqrt LatLon = namedtuple('LatLon', 'lat, lon') def distance(x, y): """Implements https://en.wikipedia.org/wiki/Haversine_formula. >>> int(distance(LatLon(55.747043, 37.655554), LatLon(55.754892, 37.657013))) 875 >>> int(distance(LatLon(60.013918, 29.718361), LatLon(59.951572, 30.205536))) 27910 """ φ1, φ2 = map(radians, [x.lat, y.lat]) λ1, λ2 = map(radians, [x.lon, y.lon]) Δφ = φ2 - φ1 Δλ = λ2 - λ1 a = sin(Δφ/2)**2 + cos(φ1) * cos(φ2) * sin(Δλ/2)**2 R = 6356863 # Earth radius in meters. return 2 * R * atan2(sqrt(a), sqrt(1 - a)) def lcs(l1, l2, eq=operator.eq): """Finds the longest common subsequence of l1 and l2. Returns a list of common parts and a list of differences. >>> lcs([1, 2, 3], [2]) ([2], [1, 3]) >>> lcs([1, 2, 3, 3, 4], [2, 3, 4, 5]) ([2, 3, 4], [1, 3, 5]) >>> lcs('banana', 'baraban') (['b', 'a', 'a', 'n'], ['a', 'r', 'b', 'n', 'a']) >>> lcs('abraban', 'banana') (['b', 'a', 'a', 'n'], ['a', 'r', 'n', 'b', 'a']) >>> lcs([1, 2, 3], [4, 5]) ([], [4, 5, 1, 2, 3]) >>> lcs([4, 5], [1, 2, 3]) ([], [1, 2, 3, 4, 5]) """ prefs_len = [ [0] * (len(l2) + 1) for _ in range(len(l1) + 1) ] for i in range(1, len(l1) + 1): for j in range(1, len(l2) + 1): if eq(l1[i - 1], l2[j - 1]): prefs_len[i][j] = prefs_len[i - 1][j - 1] + 1 else: prefs_len[i][j] = max(prefs_len[i - 1][j], prefs_len[i][j - 1]) common = [] diff = [] i, j = len(l1), len(l2) while i and j: assert i >= 0 assert j >= 0 if l1[i - 1] == l2[j - 1]: common.append(l1[i - 1]) i -= 1 j -= 1 elif prefs_len[i - 1][j] >= prefs_len[i][j - 1]: i -= 1 diff.append(l1[i]) else: j -= 1 diff.append(l2[j]) diff.extend(reversed(l1[:i])) diff.extend(reversed(l2[:j])) return common[::-1], diff[::-1] def common_part(l1, l2): common, diff = lcs(l1, l2) common_len = sum(distance(*x) for x in common) diff_len = sum(distance(*x) for x in diff) assert (not common) or common_len assert (not diff) or diff_len return 1.0 - common_len / (common_len + diff_len) class Segment: def __init__(self, segment_id, matched_route, golden_route): #TODO(mgsergio): Remove this when deal with auto golden routes. assert matched_route assert golden_route self.segment_id = segment_id self.matched_route = matched_route self.golden_route = golden_route or None def __repr__(self): return 'Segment({})'.format(self.segment_id) def as_tuple(self): return self.segment_id, self.matched_route, self.golden_route def parse_route(route): if not route: return None result = [] for edge in route.findall('RoadEdge'): start = edge.find('StartJunction') end = edge.find('EndJunction') result.append(( LatLon(float(start.find('lat').text), float(start.find('lon').text)), LatLon(float(end.find('lat').text), float(end.find('lon').text)) )) return result def parse_segments(tree, limit): segments = islice(tree.findall('.//Segment'), limit) for s in segments: ignored = s.find('Ignored') if ignored is not None and ignored.text == 'true': continue segment_id = int(s.find('.//ReportSegmentID').text) matched_route = parse_route(s.find('Route')) # TODO(mgsergio): This is a temproraty hack. All untouched segments # within limit are considered accurate, so golden path should be equal # matched path. golden_route = parse_route(s.find('GoldenRoute')) or matched_route if not matched_route and not golden_route: raise ValueError('At least one of golden route or matched route should be present') try: yield Segment(segment_id, matched_route, golden_route) except: print('Broken segment is {}'.format(segment_id)) raise def calculate(tree): ms = sorted( ( ( s.segment_id, common_part(s.golden_route, s.matched_route) ) for s in parse_segments(tree, args.limit) ), key=lambda x: -x[1] ) print('{}\t{}'.format( 'segment_id', 'intersection_weight') ) for x in ms: print('{}\t{}'.format(*x)) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser( description='Use this tool to get numerical scores on segments matching' ) parser.add_argument( 'assessed_path', type=str, help='An assessed matching file.') parser.add_argument( '-l', '--limit', type=int, default=None, help='Process no more than limit segments' ) parser.add_argument( '--merge', type=str, default=None, help='A path to a file to take matched routes from' ) args = parser.parse_args() tree = ET.parse(args.assessed_path) calculate(tree)
# Unlike arrays, sets cannot contain duplicates, so we an use a set to automatically filter out these duplicate terms terms = set() for a in range(2, 101): for b in range(2, 101): terms.add(a**b) print(len(terms))
# Consumes a natural number n and returns the sum of the numbers on the diagonals on an n by n matrix def sumOfDiagonals(n): sum = 1 current = 1 count = 1 # This question required recognizing the pattern of how the numbers on the diagonal are determined. # Once that is determined, they rest becomes straightforward while count <= (n-1)/2: for i in range(1, 5): current += 2*count sum += current count += 1 return sum print(sumOfDiagonals(1001))
# sumOfDiv consumes a number and returns the sum of the numbers divisors def sumOfDiv(n): sum = 1 i = 2 # We only need to check up until the square root of the number while i * i < n: if n % i == 0: sum += i + n // i i += 1 if i * i == n: sum += i return sum # consumes a natural number n and returns the sum of all the natural numbers below n that cannot # be written as the sum of two abundant numbers def nonAbunSum(n): Abuns = [] for i in range(6, 28123-6): if sumOfDiv(i) > i: Abuns.append(i) nonAbunsSums = [True] * (n+1) for i in range (0, len(Abuns)): for j in range (i, len(Abuns)): if Abuns[i] + Abuns[j] <= n: nonAbunsSums[Abuns[i]+Abuns[j]] = False sum = 0 for i in range(0, n+1): if nonAbunsSums[i]: sum += i return sum print (nonAbunSum(28189))
# coding: utf-8 # In[1]: # find out male and female survived proportion import pandas as pd df=pd.read_csv('data3/train.csv') # total number of passengers total_passengers=len(df) print "total number of passenngers",total_passengers # male female passengers count df_total=df.groupby('Sex').count()['PassengerId'] df_total_survived=df[df['Survived']==1].groupby('Sex').count()['PassengerId'] df=pd.DataFrame(df_total_survived/df_total,columns=["PassengerId"],index=['female','male']) df df=df.rename(columns={'PassengerId':"Proportion"}) df.to_csv('data3/male_female_survived_proportion.csv') # In[ ]:
str_symbol_map={'PLUS':'+','MULTIPLY':'*','DIVISION':'/'} def evaluate(expr): for i in str_symbol_map.iteritems(): expr=expr.replace(i[0],i[1]) return eval(expr) while True: print """ 1. Go for evaluation 2. Quit """ opt = raw_input("Enter an option: ") if opt == '1': qs = raw_input("enter number of questions: ") questions=[] for i in range(int(qs)): expr = raw_input("Enter an Expression %s:"%i) questions.append(expr) for i in questions: print evaluate(i) else: break
#!/usr/bin/env python # -*- coding: utf-8 -*- class foobase: def hello(self): print "hello" class foo: pass #obj=foo() #obj.hello() '''ubuntu@huzhi-dev:~/www/python-patterns$ python mixin-test.py Traceback (most recent call last): File "mixin-test.py", line 12, in <module> obj.hello() AttributeError: foo instance has no attribute 'hello' ubuntu@huzhi-dev:~/www/python-patterns$ ''' obj=foo() foo.__bases__ +=(foobase,) obj.hello() '''ubuntu@huzhi-dev:~/www/python-patterns$ python mixin-test.py hello ubuntu@huzhi-dev:~/www/python-patterns$ ''' '''每个类都有一个__base__属性,它是一个tuple,用来存放所有的基类。而且在运行中,可以动态改变。 所以当我们向其中增加新的基类时,再次调用原来不存在的函数,由于基类中的函数已经存在了,所以这次成功了。 这是一个最简单的应用,可以看到我们可以动态改变类的基类。有几个注意事项要说一下: 1、__bases__是一个tuple,所以增加一个值要使用tuple类型,而单个元素tuple的写法为(foobase,) 2、类必须先存在。所以,如果想使用这一技术,先要将相关的类的模块导入(import)。 由于Mix-in是一种动态技术,以多继承,对象为基础,而python正好是这样的语言,使得在python中实现这一技术非常容易。 '''
#!/usr/bin/env python # -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod, abstractproperty class Foo(object): __metaclass__ = ABCMeta # 在 Python3 中的写法是 class Foo(metaclass=ABCMeta) @abstractmethod def spam(self, a, b): pass @abstractproperty def name(self): pass class Grok(object): def spam(self, a, b): print("Grok.spam") Foo.register(Grok)
print('This is my first python game') name=input('enter your name') age=input('enter your age') print('hello',name,'you are',age,'years old' ) health=10 if int(age) >= 18: print('you are old enough to play!') wants_to_play=input('do you want to play? ').lower() if wants_to_play=='yes': print('you are starting wth', health, 'health') print('lets play!') left_or_right=input('first choce ..left/right?') if left_or_right=='left': ans=input('nice..you follow the path and reach the lake..do you swim across or go around..swim/go around?' ) if ans=='around': print('you went around and reach other side of the lake') elif ans=='across': print('you manages to get across ,but bit by a fish and lose 5 health') health-=5 ans=input('you notice a house and a river.which will you chose ..river/house? ') if ans =='house': print('you chose house and greeted by the owner..you lose 5 health ') health -=5 if health<=0: print('you have 0 health and lost the game ') else: print('you survived and won') else: print('you fell in the river and lost') else: print('you fell and lost') else: print('cya..') else: print('you are not old enough to play!')
import numpy as np """ Os pixels vizinhos são definidos conforme slide 66 do Tópico 2. Para um pixel p temos: [ (x-1, y-1); (x, y-1); (x+1, y-1) ] [ (x-1, y); p; (x+1, y) ] [ (x-1, y+1); (x, y+1); (x+1,y+1) ] Os vizinhos em relação a p são denotados como: sudoeste, sul, sudeste, leste, nordeste, norte, noroeste e oeste. Aqui temos uma lista de listas listDistancias, onde cada elemento de listDistancias é uma lista xi, onde i varia de 0 até 7. Cada uma das 8 listas xi contém o a distância do pixel x até o destino, além das coordenadas de x em relação à p (ponto atual). """ def calcula_dist(atualX, atualY, destX, destY): lista_distancias = [0, 0, 0, 0, 0, 0, 0, 0] sudoeste = np.sqrt( (destX - (atualX-1))**2 + (destY - (atualY+1))**2 ) sul = np.sqrt( (destX - (atualX))**2 + (destY - (atualY+1))**2 ) sudeste = np.sqrt( (destX - (atualX+1))**2 + (destY - (atualY+1))**2 ) leste = np.sqrt( (destX - (atualX+1))**2 + (destY - (atualY))**2 ) nordeste = np.sqrt( (destX - (atualX+1))**2 + (destY - (atualY-1))**2 ) norte = np.sqrt( (destX - (atualX))**2 + (destY - (atualY-1))**2 ) noroeste = np.sqrt( (destX - (atualX-1))**2 + (destY - (atualY-1))**2 ) oeste = np.sqrt( (destX - (atualX-1))**2 + (destY - (atualY))**2 ) lista_distancias[0] = [sudoeste, atualX-1, atualY+1] lista_distancias[1] = [sul, atualX, atualY+1] lista_distancias[2] = [sudeste, atualX+1, atualY+1] lista_distancias[4] = [leste, atualX+1, atualY] lista_distancias[7] = [nordeste, atualX+1, atualY-1] lista_distancias[6] = [norte, atualX, atualY-1] lista_distancias[5] = [noroeste, atualX-1, atualY-1] lista_distancias[3] = [oeste, atualX-1, atualY] return lista_distancias
def get_start(): start = float(input("Enter the Starting Value for the counter: ")) return start def get_stop(): stop = float(input("Enter the Stopping Value for the counter: ")) return stop def get_increment(): increment = float(input("Enter the value you would like to increment by: ")) return increment def display_results(start, stop, increment): while start <= stop: print (start) start = start + increment def main(): start = get_start() stop = get_stop() increment = get_increment() display_results(start, stop, increment) # Main # This program counts based off user's inputs main()
def calculateOrder(shipping, tax, total): order = total + shipping + tax return order def calculateShipping(total): if total >= 100: shipping = 0 else: shipping = total * 0.1 return shipping def calculateTax(total): tax = total * 0.07 return tax def displayResults(tax, total, order, shipping, quantity, price): print("The total quantity is: " + str(quantity) + ", The price per item is: " + str(price) + ", The shipping cost is: " + str(shipping) + ", The order total is: " + str(order)) def getTotal(quantity, price): total = price * quantity return total # Main print("Enter the quantity of items: ") quantity = int(input()) print("Enter the price for the items: ") price = float(input()) total = getTotal(quantity, price) tax = calculateTax(total) shipping = calculateShipping(total) order = calculateOrder(total, shipping, tax) displayResults(tax, total, order, shipping, quantity, price)
def get_quantity(): print ("Enter the number of items: ") quantity = int(input()) return quantity def get_price(): print ("Enter the price per item: ") price = float(input()) return price def calculate_total(quantity, price): total = (price * quantity) return total def calculate_tax(total): tax = (0.7 * total) return tax def calculate_cost(total, tax): cost = (total + tax) return cost def display_results(quantity, price, total, tax, cost): print ("The number of items is: " + str(quantity)) print ("The price per item is: $" + str(price)) print ("The total price is: $" + str(total)) print ("The amount of tax added is: $" + str(tax)) print ("The total cost will be: $" + str(cost)) def main(): quantity = get_quantity() price = get_price() total = calculate_total(quantity, price) tax = calculate_tax(total) cost = calculate_cost(tax, total) display_results(quantity, price, total, tax, cost) #Main #This program calculates total cost including tax from quantity and price per item main()
for i in range(1,100): fizz = False; buzz = False; if i % 3 == 0: fizz = True; if i % 5 == 0: buzz = True; if fizz: if buzz: print("fizzbuzz"); else: print("fizz"); elif fizz: print("fizz"); else: print(i);
#Python code to do transpose of a given matrix def display_matrix(matrix): """ To display a given matrix. :param matrix: Multi dimensional matrix :return: Nothing """ print("__________________") for each_row in matrix: print(each_row) print("__________________") input_matrix = [ [1,2,3,4], [5,6,7,8], [9,0,1,2] ] ##################################################################### #Logic using 'for' loops transposed_matrix = [] for each_row_index in range(len(input_matrix[0])): temp_lst = [] for each_row in input_matrix: temp_lst.append(each_row[each_row_index]) print(temp_lst) transposed_matrix.append(temp_lst) print("~~~~~~INPUT~~~~~~~~~~") display_matrix(input_matrix) print("~~~~~~OUTPUT~~~~~~~~~~") display_matrix(transposed_matrix) ##################################################################### #Logic using List Comprehension transposed_matrix2 = [[each_row[each_row_index] for each_row in input_matrix] for each_row_index in range(len(input_matrix[0]))] print("~~~~~~INPUT~~~~~~~~~~") display_matrix(input_matrix) print("~~~~~~OUTPUT~~~~~~~~~~") display_matrix(transposed_matrix2)
a = 2 sum = 0 temp = a for i in range(5): temp = temp*a sum += temp
import pandas as pd #數字處理 # data = pd.Series([6, 8, -8, 689, 9]) # #print(data.sum(), data.prod())#相加總合 相乘總和 # #print(data.mean(), data.std()) #平均 標準差 # print(data.nlargest(3)) #前三大數 # print(data.nsmallest(2)) #前兩小數 #字串處理 data =pd.Series(["你好", "Python", "Pandas"],index=["a","b","c"]) #可自行更改索引 print(data.str.lower()) #轉小寫 print(data.str.upper()) #轉大寫 print(data.str.len()) #每個字串長度 print(data.str.cat(sep="-")) #以-合併字串 print(data.str.contains("P")) #判斷是否有P print(data.str.replace("你好", "Hello")) #將你好取代成Hollo data=data.str.replace("你好","Hollo") print("資料型態", data.dtype) print("資料數量", data.size) print("資料索引", data.index) print(data[0],data["a"])
import pygame as pg #pg.init() #設定視窗背景 width, height = 640, 480 screen = pg.display.set_mode((width, height)) pg.display.set_caption("Sean's game") bg = pg.Surface(screen.get_size()) bg = bg.convert() bg.fill((255,255,255)) #藍球建立 ball = pg.Surface((70,70)) #建立球矩形繪圖區 ball.fill((255,255,255)) #矩形區塊背景為白色 pg.draw.circle(ball, (0,0,255), (35,35), 35, 0) #畫藍色球 rect = ball.get_rect() #取得球矩形區塊 rect.center = (320,240) #球起始位置 x, y = rect.topleft #球左上角坐標 speed = 3 #球運動速度 clock = pg.time.Clock() #建立時間元件 #關閉程式的程式碼 running = True while running: clock.tick(30) #每秒執行30次 for event in pg.event.get(): if event.type == pg.QUIT: running = False x += speed #改變水平位置 rect.center = (x,y) #坐標差異讓它移動 if(rect.left <= 0 or rect.right >= screen.get_width()): #到達左右邊界 speed *= -1 #正負值交換 screen.blit(bg, (0,0)) screen.blit(ball, rect.topleft) #繪製藍球 pg.display.update() #更新視窗 #pg.quit()
# 입력: 첫째 줄에 단어가 주어진다. # 단어는 알파벳 소문자와 대문자로만 이루어져 있으며, 길이는 100을 넘지 않는다. # 길이가 0인 단어는 주어지지 않는다. # 출력: 입력으로 주어진 단어를 열 개씩 끊어서 한 줄에 하나씩 출력한다. # 단어의 길이가 10의 배수가 아닌 경우에는 마지막 줄에는 10개 미만의 글자만 출력할 수도 있다. # words = input() temp = "" n = 0 for i in words: temp += i n += 1 if n % 10 == 0: print(temp) temp = "" if temp != "": print(temp)
def partition(left_index, right_index, list_to_sort): if left_index >= right_index: return pivot_index = left_index j = pivot_index for i in range(left_index + 1, right_index + 1): if list_to_sort[i] < list_to_sort[pivot_index]: j += 1 list_to_sort[i], list_to_sort[j] = list_to_sort[j], list_to_sort[i] new_pivot_index = j # 복습시 가독성을 위해 임시 변수 설정 list_to_sort[pivot_index], list_to_sort[new_pivot_index] = list_to_sort[new_pivot_index], list_to_sort[pivot_index] return new_pivot_index def quick_coord_sort(left_index, right_index, list_to_sort): if left_index >= right_index: return pivot_index = partition(left_index, right_index, list_to_sort) #print(pivot_index) quick_coord_sort(left_index, pivot_index - 1, list_to_sort) quick_coord_sort(pivot_index + 1, right_index, list_to_sort) example = [33, 12, 14, 2, 3] quick_coord_sort(0, len(example) - 1, example) print(example)
# 입력: 첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다. # 출력: 첫째 줄부터 N번째 줄까지 차례대로 별을 출력한다. N = int(input()) line = "" for i in range(1, N+1): line += "*" print(line)
# https://ratsgo.github.io/data%20structure&algorithm/2017/10/16/countingsort/ # digit 은 1, 10, 100... def counting_sort(arr, digit): n = len(arr) # 배열의 크기에 맞는 output 배열을 생성하고 10개의 0을 가진 count란 배열을 생성한다. output = [0] * n count = [0] * 10 # digit, 자릿수에 맞는 count에 += 1을 한다. for i in range(0, n): index = int(arr[i] / digit) count[index % 10] += 1 print(count) # 기존 count 값을 사용해 count 배열에 count 가 아닌 (중요) 위치값을 저장 for i in range(1, 10): count[i] += count[i - 1] # count print(i, count[i]) print(count) # 앞서 count 에 저장한 위치값을 기반으로 output 에 arr 들을 담는다. i = n - 1 while i >= 0: index = int(arr[i] / digit) output[count[index % 10] - 1] = arr[i] count[index % 10] -= 1 i -= 1 # arr 를 결과물에 다시 재할당한다. for i in range(0, n): arr[i] = output[i] # Method to do Radix Sort def radix_sort(arr): # arr 배열중에서 maxValue 를 잡아서 어느 digit, 자릿수까지 반복하면 될지를 정한다. max_val = max(arr) # 자릿수마다 countingSorting 을 시작한다. digit = 1 while int(max_val / digit) > 0: counting_sort(arr, digit) digit *= 10 arr = [170, 45, 75, 90, 802, 24, 2, 66] # arr = [4, 2, 1, 5, 7, 2] radix_sort(arr) for i in range(len(arr)): print(arr[i], end=" ")
def num_to_base(n, b): convert = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" if n == 0: return 0 digits = ['0'] while n: to_append = int(n % b) digits.append(convert[to_append]) n //= b # 역순을 리턴 return digits[::-1]
def BinarySearch(num_list, target): num_list.sort() start = 0 end = len(num_list) - 1 mid = (start + end) // 2 while start <= end: if num_list[mid] == target: return mid if num_list[mid] < target: start = mid + 1 continue if num_list[mid] > target: end = mid - 1 return -1
class MinHeap: def __init__(self, arg_list=None): self.queue = [0] if arg_list is not None: self.queue += arg_list for i in range(len(arg_list)//2, 0, -1): self.min_heapify(i) def last(self): return len(self.queue) - 1 @staticmethod def parent(i): return i//2 @staticmethod def left(i): return i * 2 @staticmethod def right(i): return i * 2 + 1 def min_heapify(self, i): left = self.left(i) right = self.right(i) smallest = i if left <= self.last() and self.queue[left] < self.queue[i]: smallest = left if right <= self.last() and self.queue[right] < self.queue[i]: smallest = right if self.queue[i] != self.queue[smallest]: self.queue[i], self.queue[smallest] = self.queue[smallest], self.queue[i] self.min_heapify(smallest) def insert(self, n): self.queue.append(n) i = self.last() while i > 1: parent = self.parent(i) if self.queue[parent] > n: self.queue[parent], self.queue[i] = self.queue[i], self.queue[parent] i = parent else: break def delete(self): i = self.last() self.queue[1], self.queue[i] = self.queue[i], self.queue[1] self.queue.pop() self.min_heapify(1) min_heap = MinHeap([4, 5, 3, 77, 2]) print(min_heap.queue) min_heap.delete() print(min_heap.queue) min_heap.insert(-1) print(min_heap.queue)
# https://www.acmicpc.net/problem/2447 # 입력: 첫째 줄에 N이 주어진다. # N은 항상 3의 제곱꼴인 수이다. (3, 9, 27, ...) # (N=3^k, 1 ≤ k < 8) # 출력: 첫째 줄부터 N번째 줄까지 별을 출력한다. import math import sys def draw_star(ret, power, first_point_row, first_point_col): if power == 1: ret[first_point_row + 1][first_point_col + 1] = " " return ret new_power = power - 1 unit_dist = 3 ** new_power unit_dist_doubled = 2 * unit_dist ret = draw_star(ret, new_power, first_point_row, first_point_col) ret = draw_star(ret, new_power, first_point_row, first_point_col + unit_dist) ret = draw_star(ret, new_power, first_point_row, first_point_col + unit_dist_doubled) ret = draw_star(ret, new_power, first_point_row + unit_dist, first_point_col) # draw empty for row in range(first_point_row + unit_dist, first_point_row + unit_dist_doubled): for col in range(first_point_col + unit_dist, first_point_col + unit_dist_doubled): ret[row][col] = " " ret = draw_star(ret, new_power, first_point_row + unit_dist, first_point_col + unit_dist_doubled) ret = draw_star(ret, new_power, first_point_row + unit_dist_doubled, first_point_col) ret = draw_star(ret, new_power, first_point_row + unit_dist_doubled, first_point_col + unit_dist) ret = draw_star(ret, new_power, first_point_row + unit_dist_doubled, first_point_col + unit_dist_doubled) return ret N = int(sys.stdin.readline().rstrip()) target_power = round(math.log(N, 3)) stars = [["*" for col in range(N)] for row in range(N)] stars = draw_star(stars, target_power, 0, 0) for row in stars: print(*row, sep="") # 느려서 실패한 문제.
from la.vector import Vector if __name__ == "__main__": # vector = [5, 2] # vector2 = [3, 1] # zero_2 = [0, 0] # zero_3 = [0, 0, 0] vector = Vector([5, 2]) vector2 = Vector([3, 1]) zero_2 = Vector.zero(2) zero_3 = Vector.zero(3) print("vector = {}".format(vector)) print("vector2 = {}".format(vector2)) print("zero_2 = {}".format(zero_2)) print("zero_3 = {}".format(zero_3)) print("------") # len(vector) = 2 # vector[0] = 5, vector[1] = 2 print("len(vector) = {}".format(len(vector))) print("vector[0] = {}, vector[1] = {}".format(vector[0], vector[1])) print("------") # [5, 2] + [3, 1] = [8, 3] # [5, 2] + [0, 0] = [5, 2] # [5, 2] - [3, 1] = [2, 1] # [5, 2] - [0, 0] = [5, 2] # [5, 2] * 3 = [15, 6] # 3 * [5, 2] = [15, 6] # [5, 2] / 2 = [2.5, 1.0] # +[5, 2] = [5, 2] # -[5, 2] = [-5, -2] print("{} + {} = {}".format(vector, vector2, vector + vector2)) print("{} + {} = {}".format(vector, zero_2, vector + zero_2)) print("{} - {} = {}".format(vector, vector2, vector - vector2)) print("{} - {} = {}".format(vector, zero_2, vector - zero_2)) print("{} * {} = {}".format(vector, 3, vector * 3)) print("{} * {} = {}".format(3, vector, 3 * vector)) print("{} / {} = {}".format(vector, 2, vector / 2)) print("+{} = {}".format(vector, +vector)) print("-{} = {}".format(vector, -vector)) print("------") # [5, 2].norm() = 5.385164807134504 # [3, 1].norm() = 3.1622776601683795 # [0, 0].norm() = 0.0 print("{}.norm() = {}".format(vector, vector.norm())) print("{}.norm() = {}".format(vector2, vector2.norm())) print("{}.norm() = {}".format(zero_2, zero_2.norm())) # [5, 2].normalize() = [0.9284766908852593, 0.3713906763541037] # [3, 1].normalize() = [0.9486832980505138, 0.31622776601683794] # Cannot normalize zero vector [0, 0] print("{}.normalize() = {}".format(vector, vector.normalize())) print("{}.normalize() = {}".format(vector2, vector2.normalize())) try: print("{}.normalize() = {}".format(zero_2, zero_2.normalize())) except ZeroDivisionError: print("Cannot normalize zero vector {}".format(zero_2)) # [5, 2].normalize().norm() = 1.0 # [3, 1].normalize().norm() = 0.9999999999999999 print("{}.normalize().norm() = {}".format(vector, vector.normalize().norm())) print("{}.normalize().norm() = {}".format(vector2, vector2.normalize().norm()))
from PIL import Image from io import BytesIO filename = "test.jpg" pil_image = Image.open(filename) width, height = pil_image.size print("width",width ) print("height",height ) r_width = 400 r_height = int(r_width*((height/width))) pil_image = pil_image.resize((width, height), Image.ANTIALIAS) pil_image_rgb = pil_image.convert('RGB') pil_image_rgb.save("res.jpg", format='JPEG', quality=90)
########################### # 6.00.2x Problem Set 1: Space Cows from ps1_partition import get_partitions import time #================================ # Part A: Transporting Space Cows #================================ def load_cows(filename): """ Read the contents of the given file. Assumes the file contents contain data in the form of comma-separated cow name, weight pairs, and return a dictionary containing cow names as keys and corresponding weights as values. Parameters: filename - the name of the data file as a string Returns: a dictionary of cow name (string), weight (int) pairs """ cow_dict = dict() f = open(filename, 'r') for line in f: line_data = line.split(',') cow_dict[line_data[0]] = int(line_data[1]) return cow_dict # Problem 1 def greedy_cow_transport(cows,limit=10): """ Uses a greedy heuristic to determine an allocation of cows that attempts to minimize the number of spaceship trips needed to transport all the cows. The returned allocation of cows may or may not be optimal. The greedy heuristic should follow the following method: 1. As long as the current trip can fit another cow, add the largest cow that will fit to the trip 2. Once the trip is full, begin a new trip to transport the remaining cows Does not mutate the given dictionary of cows. Parameters: cows - a dictionary of name (string), weight (int) pairs limit - weight limit of the spaceship (an int) Returns: A list of lists, with each inner list containing the names of cows transported on a particular trip and the overall list containing all the trips """ # TODO: Your code here num_passengers = len(cows) max_limit = limit pass_list = dict_to_list(cows) num_transported = 0 transport_list = [] while num_transported < num_passengers: trans_list, remain_list = greedy(pass_list, max_limit) transport_list.append(trans_list) num_transported += len(trans_list) pass_list = remain_list return transport_list def greedy(pass_list, max_weight): pass_list = sorted(pass_list, key=Passenger.getWeight, reverse=True) cur_weight = 0 transport_names = [] remaining_list = [] for item in pass_list: if item.getWeight() + cur_weight <= max_weight: transport_names.append(item.getName()) cur_weight += item.getWeight() else: remaining_list.append(item) return transport_names, remaining_list # Problem 2 def brute_force_cow_transport(cows,limit=10): """ Finds the allocation of cows that minimizes the number of spaceship trips via brute force. The brute force algorithm should follow the following method: 1. Enumerate all possible ways that the cows can be divided into separate trips 2. Select the allocation that minimizes the number of trips without making any trip that does not obey the weight limitation Does not mutate the given dictionary of cows. Parameters: cows - a dictionary of name (string), weight (int) pairs limit - weight limit of the spaceship (an int) Returns: A list of lists, with each inner list containing the names of cows transported on a particular trip and the overall list containing all the trips """ # TODO: Your code here pass_list = dict_to_list(cows) partitions = get_partitions(pass_list) min_num_trips = len(pass_list) min_part = None for part_list in partitions: trip_weights = get_partition_weight(part_list) valid_trip = all([x < limit for x in trip_weights]) if valid_trip and len(trip_weights) < min_num_trips: min_num_trips = len(trip_weights) min_part = part_list pass_list = get_names_mult_trips(min_part) return pass_list # Problem 3 def compare_cow_transport_algorithms(): """ Using the data from ps1_cow_data.txt and the specified weight limit, run your greedy_cow_transport and brute_force_cow_transport functions here. Use the default weight limits of 10 for both greedy_cow_transport and brute_force_cow_transport. Print out the number of trips returned by each method, and how long each method takes to run in seconds. Returns: Does not return anything. """ # TODO: Your code here pass class Passenger: def __init__(self, name, weight): self.name = name self.weight = weight self.transported = False def getWeight(self): return self.weight def getName(self): return self.name def getTransported(self): return self.transported def __str__(self): out_str = "{0}:{1}".format(self.getName(), self.getWeight()) return out_str def dict_to_list(pass_dict): pass_list = [] for k, v in pass_dict.items(): passenger = Passenger(k, v) pass_list.append(passenger) return pass_list def get_weight(pass_list): cur_weight = 0 for item in pass_list: cur_weight += item.getWeight() return cur_weight def get_partition_weight(part_list): part_weight = [] for part in part_list: part_weight.append(get_weight(part)) return part_weight def get_names_one_trip(pass_list): name_list = [] for item in pass_list: name_list.append(item.getName()) return name_list def get_names_mult_trips(trip_list): trip_names = [] for pass_list in trip_list: trip_names.append(get_names_one_trip(pass_list)) return trip_names """ Here is some test data for you to see the results of your algorithms with. Do not submit this along with any of your answers. Uncomment the last two lines to print the result of your problem. """ cows = load_cows("ps1_cow_data.txt") limit=10 #cows = {"Jesse": 6, "Maybel": 3, "Callie": 2, "Maggie": 5} #limit=10 #cows = {'Horns': 25, 'Miss Bella': 25, 'Boo': 20, 'MooMoo': 50, # 'Lotus': 40, 'Milkshake': 40} #limit = 100 #cows = {'Daisy': 50, 'Betsy': 65, 'Buttercup': 72} #limit = 75 print(cows) print('Greedy') start = time.time() print(greedy_cow_transport(cows, limit)) end = time.time() print(end - start) print('Brute force') start = time.time() print(brute_force_cow_transport(cows, limit)) end = time.time() print(end - start)
from parsing.token import Token, TokenType """ A lexical analyser for LTL. The class is initialized with a string containing the LTL formula, and tokens can then be retrieved from the string in a lazy fashion by invoking the get_next_token() method. Only significant tokens are returned by the method, meaning that white-space characters are gobbled up and ignored. As the lexical analyses takes place lazily, errors are only raised when the analysis encounters illegal characters in the string. """ class Lexer(object): def __init__(self, text): """ Initializes the lexical analyser with the input formula to tokenize, together with the counters. The look-ahead character is also bootstrapped by immediately reading the first character from the stream. """ self.text = text self._pos, self._col, self._line = -1, 0, 1 # Initialize look-ahead to the first character in the input stream. self._look_ahead = '' self._read_next_char() def _error(self, message, line, col): hint = self.text[:col - 1] + '^^^' + self.text[col - 1:] raise Exception('Lexical error (%s,%s): %s. Hint: %s.' % (line, col, message, hint)) def _read_next_char(self): """ Reads the next character from the string and updates the look ahead character or sets it to None if the string is depleted. """ self._pos, self._col = self._pos + 1, self._col + 1 if self._pos > len(self.text) - 1: # We have reached the end of the input string. self._look_ahead = None else: # Get next character from the input string. self._look_ahead = self.text[self._pos] def _skip_whitespace(self): """ Eats up all the white space character by character until a non-white space character is encountered in the input stream. """ while self._look_ahead is not None and self._look_ahead.isspace(): if self._look_ahead == '\n' or self._look_ahead == '\r\n': self._line, self._col = self._line + 1, 0 self._read_next_char() def get_next_token(self): """ Returns the next token from the string. """ if Token.is_whitespace(self._look_ahead): self._skip_whitespace() if self._look_ahead is None: return Token(TokenType.EOF, '<EOF>', self._line, self._col) elif Token.is_alpha(self._look_ahead): return self._get_word() elif Token.is_operator(self._look_ahead): return self._get_operator() elif Token.is_symbol(self._look_ahead): return self._get_symbol() return self._error('invalid character: \'' + self._look_ahead + '\'', self._line, self._col) def _get_word(self): """ Returns the next word string from the input stream as a token. """ word, line, col = '', self._line, self._col while Token.is_alpha(self._look_ahead): word += self._look_ahead self._read_next_char() return Token(Lexer._token_type_from_word(word), word, line, col) def _get_operator(self): """ Returns the next operator from the input stream as a token. """ operator, line, col = '', self._line, self._col while Token.is_operator(self._look_ahead): operator += self._look_ahead self._read_next_char() return Token(Lexer._token_type_from_operator(operator), operator, line, col) def _get_symbol(self): """ Returns the next symbol from the input stream as a token. """ symbol, line, col = self._look_ahead, self._line, self._col self._read_next_char() return Token(Lexer._token_type_from_symbol(symbol), symbol, line, col) def _token_type_from_word(value): """ Returns the temporal operator or proposition token type from the specified word value. """ return { 'G': TokenType.G, 'X': TokenType.X, 'F': TokenType.F, 'U': TokenType.U, 'W': TokenType.W, 'R': TokenType.R }.get(value, TokenType.ATOM) def _token_type_from_operator(value): """ Returns the multi-character token type from the specified symbol value. """ return { '&&': TokenType.AND, '||': TokenType.OR, '->': TokenType.IMPL }.get(value) def _token_type_from_symbol(value): """ Returns the single-character token type from the specified symbol value. """ return { '!': TokenType.NOT, '(': TokenType.LPAR, ')': TokenType.RPAR }.get(value)
#1 list.append(obj) #Appends object obj to list #2 list.count(obj) #Returns count of how many times obj occurs in list #3 list.extend(seq) #Appends the contents of seq to list # https://stackoverflow.com/questions/252703/difference-between-append-vs-extend-list-methods-in-python #4 list.index(obj) #Returns the lowest index in list that obj appears #5 list.insert(index, obj) #Inserts object obj into list at offset index #6 list.pop(obj=list[-1]) #Removes and returns last object or obj from list #7 list.remove(obj) #Removes object obj from list #8 list.reverse() #Reverses objects of list in place #9 list.sort([func]) #Sorts objects of list, use compare func if given #1 list.append(obj) cat_list = ["not eating", "not playing", "on a bed", "is sleeping"] cat_list.append("A Mongolian Cat") for state in cat_list: print("This cat is " + state) print(cat_list) even = [2, 4, 6, 8] odd = [1, 3, 5, 7, 9] numbers = even + odd numbers_in_order = sorted(numbers) print(numbers) print(numbers_in_order) if numbers == numbers_in_order: print("The lists are equal") else: print("The lists are not equal") if numbers_in_order == sorted(numbers): print("The lists are equal") else: print("The lists are not equal") #2 list.count(obj) aList = [123, 'xyz', 'zara', 'abc', 123] print ("Count for 123 : ", aList.count(123)) print ("Count for zara : ", aList.count('zara')) #3 list.extend(seq) aList = [123, 'xyz', 'zara', 'abc', 123] bList = [2009, 'manni'] aList.extend(bList) print("Extended List : ", aList) #4 list.index(obj) aList = [123, 'xyz', 'zara', 'abc', 'xyz'] print("Index for xyz : ", aList.index( 'xyz' )) print("Index for zara : ", aList.index( 'zara' )) #5 list.insert(index, obj) aList = [123, 'xyz', 'zara', 'abc'] aList.insert( 3, 2009) print("Final List : ", aList) #6 list.pop(obj=list[-1]) aList = [123, 'xyz', 'zara', 'abc'] print("A List : ", aList.pop(1)) print("B List : ", aList.pop(2)) print(aList) #7 list.remove(obj) aList = [123, 'xyz', 'zara', 'abc', 'xyz'] aList.remove('xyz') print("List : ", aList) aList.remove('abc') print("List : ", aList) #8 list.reverse() aList = [123, 'xyz', 'zara', 'abc', 'xyz'] aList.reverse() print ("List : ", aList) #9 list.sort([func]) aList = ['xyz', 'zara', 'abc', 'xyz'] aList.sort() print("List : ", aList) #Indexing, Slicing, and Matrixes L = ['spam', 'Spam', 'SPAM!'] print(L[2]) print(L[-2]) print(L[1:])
######################## Decorator ################################# # Decorator functions are software design patterns. They dynamically alter the functionality of a function, method, or # class without having to directly use subclasses or change the source code of the decorated function. When used # correctly, decorators can become powerful tools in the development process. This topic covers implementation and # applications of decorator functions in Python. # This simplest decorator does nothing to the function being decorated. Such # minimal decorators can occasionally be used as a kind of code markers. def super_secret_function(f): return f @super_secret_function # <--- is the same as ----> my_function = super_secret_function(my_function) def my_function(): print("This is my secret function.") #It is important to bear this in mind in order to understand how the decorators work. This "unsugared" syntax makes #it clear why the decorator function takes a function as an argument, and why it should return another function. It #also demonstrates what would happen if you don't return a function #This is the decorator def print_args(func): def inner_func(*args, **kwargs): print(args) print(kwargs) return func(*args, **kwargs) #Call the original function with its arguments return inner_func @print_args def multiply(num_a, num_b): return num_a * num_b print(multiply(3, 5)) #Output: # (3,5) - This is actually the 'args' that the function receives. # {} - This is the 'kwargs', empty because we didn't specify keyword arguments. # 15 - The result of the function. #Decorator class class Decorator(object): """Simple decorator class.""" def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print('Before the function call.') res = self.func(*args, **kwargs) print('After the function call.') return res @Decorator def testfunc(): print('Inside the function.') testfunc() # Before the function call. # Inside the function. # After the function call. #Decorator with arguments def decoratorfactory(message): def decorator(func): def wrapped_func(*args, **kwargs): print('The decorator wants to tell you: {}'.format(message)) return func(*args, **kwargs) return wrapped_func return decorator @decoratorfactory('Hello World') def test(): pass test() #Chain of function decorators def make_bold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def make_italic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped def make_underline(fn): def wrapped(): return "<u>" + fn() + "</u>" return wrapped @make_bold @make_italic @make_underline def hello(): return "hello world" print(hello()) ## returns "<b><i><u>hello world</u></i></b>" import sys def my_range(n: int): print("my_range starts") start = 0 while start < n: print("my_range is returning {}".format(start)) yield start start += 1 big_range = range(5) # big_range = my_range(5) # _ = input("line 14") print("big_range is {} bytes".format(sys.getsizeof(big_range))) # create a list containing all the values in big_range big_list = [] # _ = input("line 22") for val in big_range: # _ = input("line 24 - inside loop") big_list.append(val) print("big_list is {} bytes".format(sys.getsizeof(big_list))) print(big_range) print(big_list) print("looping again ... or not") for i in big_range: print("i is {}".format(i))
# coding: utf-8 # # while loops # # The **while** statement in Python is one of most general ways to perform iteration. # A **while** statement will repeatedly execute a single statement or group of # statements as long as the condition is true. The reason it is called a 'loop' # is because the code statements are looped through over and over again until the condition is no longer met. # # The general format of a while loop is: # # while test: # code statement # else: # final code statements # # Let’s look at a few simple while loops in action. # https://www.learnpython.org/en/Loops # In[2]: x = 0 while x < 10: print('x is currently: ',x) print(' x is still less than 10, adding 1 to x') x+=1 # Notice how many times the print statements occurred and how the while loop kept going until the True condition was # met, which occurred once x==10. Its important to note that once this occurred the code stopped. # Lets see how we could add an else statement: # In[3]: x = 0 while x < 10: print ('x is currently: ',x) print (' x is still less than 10, adding 1 to x') x+=1 else: print ('All Done!') # #break, continue, pass # # We can use break, continue, and pass statements in our loops to add additional functionality for various cases. # The three statements are defined by: # # break: Breaks out of the current closest enclosing loop. # continue: Goes to the top of the closest enclosing loop. # pass: Does nothing at all. # # # Thinking about **break** and **continue** statements, the general format of the while loop looks like this: # # while test: # code statement # if test: # break # if test: # continue # else: # # **break** and **continue** statements can appear anywhere inside the loop’s body,but we will usually # put them further nested in conjunction with an **if** statement to perform an action based on some condition. # # Lets go ahead and look at some examples! # In[6]: x = 0 while x < 10: print ('x is currently: ',x) print (' x is still less than 10, adding 1 to x') x+=1 if x ==3: print ('x==3') else: print ('continuing...') continue # Note how we have a printed statement when x==3, and a continue being printed out as we # continue through the outer while loop. Let's put in a break once x ==3 and see if the result makes sense: # In[7]: x = 0 while x < 10: print('x is currently: ',x) print(' x is still less than 10, adding 1 to x') x+=1 if x ==3: print('Breaking because x==3') break else: print('continuing...') continue # Note how the other else statement wasn't reached and continuing was never printed! # # After these brief but simple examples, you should feel comfortable using while statements in your code. # # **A word of caution however! It is possible to create an infinitely running loop with while # statements. For example:** # In[ ]: # DO NOT RUN THIS CODE!!!! while True: print ('Uh Oh infinite Loop!') customers = [ dict(id=1, total=200, coupon_code='F20'), # F20: fixed, $20 dict(id=2, total=150, coupon_code='P30'), # P30: percent, 30% dict(id=3, total=100, coupon_code='P50'), # P50: percent, 50% dict(id=4, total=110, coupon_code='F15'), # F15: fixed, $15 ] for customer in customers: code = customer['coupon_code'] if code == 'F20': customer['discount'] = 20.0 elif code == 'F15': customer['discount'] = 15.0 elif code == 'P30': customer['discount'] = customer['total'] * 0.3 elif code == 'P50': customer['discount'] = customer['total'] * 0.5 else: customer['discount'] = 0.0 for customer in customers: print(customer['id'], customer['total'], customer['discount'])
wines = (1, 4, 2, 3, 9) #wines = (1, 4) memo = [[-1 for i in range(0, len(wines))] for j in range(0, len(wines))] def chooseWineMemo(year, left, right): global numCalls numCalls += 1 print("chooseWine y:" + str(year) + " l:" + str(left) + " r:" + str(right)) if memo[left][right] != -1: return memo[left][right] if left == right: return year * wines[left] maxProfit = max(wines[left] * year + chooseWineMemo(year + 1, left + 1, right), wines[right] * year + chooseWineMemo(year + 1, left, right - 1)) memo[left][right] = maxProfit return maxProfit def chooseWine(year, left, right): global numCalls numCalls += 1 print("chooseWine y:" + str(year) + " l:" + str(left) + " r:" + str(right)) if left == right: return year * wines[left] return max(wines[left] * year + chooseWine(year + 1, left + 1, right), wines[right] * year + chooseWine(year + 1, left, right - 1)) numCalls = 0 maxProfit = chooseWine(1, 0, len(wines) - 1) print("max profit is: " + str(maxProfit) + " num calls:" + str(numCalls)) numCalls = 0 maxProfit = chooseWineMemo(1, 0, len(wines) - 1) print(memo) print("max profit is: " + str(maxProfit) + " num calls:" + str(numCalls))
## ID: 20180373 NAME: Kim Hyeonji (김현지) ###################################################################################### # Problem 2a # minimax value of the root node: 6 # pruned edges: h, m, x ###################################################################################### from util import manhattanDistance from game import Directions import random, util, math from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def __init__(self): self.lastPositions = [] self.dc = None def getAction(self, gameState): """ getAction chooses among the best options according to the evaluation function. getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} ------------------------------------------------------------------------------ Description of GameState and helper functions: A GameState specifies the full game state, including the food, capsules, agent configurations and score changes. In this function, the |gameState| argument is an object of GameState class. Following are a few of the helper methods that you can use to query a GameState object to gather information about the present state of Pac-Man, the ghosts and the maze. gameState.getLegalActions(): Returns the legal actions for the agent specified. Returns Pac-Man's legal moves by default. gameState.generateSuccessor(agentIndex, action): Returns the successor state after the specified agent takes the action. Pac-Man is always agent 0. gameState.getPacmanState(): Returns an AgentState object for pacman (in game.py) state.configuration.pos gives the current position state.direction gives the travel vector gameState.getGhostStates(): Returns list of AgentState objects for the ghosts gameState.getNumAgents(): Returns the total number of agents in the game gameState.getScore(): Returns the score corresponding to the current state of the game It corresponds to Utility(s) The GameState class is defined in pacman.py and you might want to look into that for other helper methods, though you don't need to. """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (oldFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() oldFood = currentGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) ###################################################################################### # Problem 1a: implementing minimax class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (problem 1) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Terminal states can be found by one of the following: pacman won, pacman lost or there are no legal moves. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 Directions.STOP: The stop direction, which is always legal gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game gameState.getScore(): Returns the score corresponding to the current state of the game It corresponds to Utility(s) gameState.isWin(): Returns True if it's a winning state gameState.isLose(): Returns True if it's a losing state self.depth: The depth to which search should continue """ # BEGIN_YOUR_ANSWER (our solution is 30 lines of code, but don't worry if you deviate from this) # raise NotImplementedError # remove this line before writing code def value(state, depth, agentIndex, isMinValue): if isMinValue == 1: v = min_value(state, depth, 1) elif agentIndex == state.getNumAgents()-1 : v = max_value(state, depth+1) else : v = min_value(state, depth, agentIndex+1) return v def max_value(state, depth): v = -math.inf if depth == self.depth or state.isWin() or state.isLose(): v = self.evaluationFunction(state) else : for action in state.getLegalActions(): v = max(v, value(state.generateSuccessor(0, action), depth, 1, 1)) return v def min_value(state, depth, agentIndex): v = math.inf if depth == self.depth or state.isWin() or state.isLose(): v = self.evaluationFunction(state) else : for action in state.getLegalActions(agentIndex): v = min(v, value(state.generateSuccessor(agentIndex, action), depth, agentIndex, 0)) return v v = -math.inf move = Directions.STOP for action in gameState.getLegalActions(): temp = value(gameState.generateSuccessor(0, action), 0, 1, 1) if temp > v : v = temp move = action return move # END_YOUR_ANSWER ###################################################################################### # Problem 2b: implementing alpha-beta class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (problem 2) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ # BEGIN_YOUR_ANSWER (our solution is 42 lines of code, but don't worry if you deviate from this) # raise NotImplementedError # remove this line before writing code def value(state, alpha, beta, depth, agentIndex, isMinValue): if isMinValue == 1: v = min_value(state, alpha, beta, depth, 1) elif agentIndex == state.getNumAgents()-1 : v = max_value(state, alpha, beta, depth+1) else : v = min_value(state, alpha, beta, depth, agentIndex+1) return v def max_value(state, alpha, beta, depth): v = -math.inf if depth == self.depth or state.isWin() or state.isLose(): v = self.evaluationFunction(state) else : for action in state.getLegalActions(): v = max(v, value(state.generateSuccessor(0, action), alpha, beta, depth, 1, 1)) if v >= beta : return v alpha = max(alpha, v) return v def min_value(state, alpha, beta, depth, agentIndex): v = math.inf if depth == self.depth or state.isWin() or state.isLose(): v = self.evaluationFunction(state) else : for action in state.getLegalActions(agentIndex): v = min(v, value(state.generateSuccessor(agentIndex, action), alpha, beta, depth, agentIndex, 0)) if v <= alpha: return v beta = min(beta, v) return v alpha = -math.inf beta = -math.inf v = -math.inf move = Directions.STOP for action in gameState.getLegalActions(): temp = value(gameState.generateSuccessor(0, action), alpha, beta, 0, 1, 1) if temp > v : v = temp move = action alpha = max(alpha, v) return move # END_YOUR_ANSWER ###################################################################################### # Problem 3a: implementing expectimax class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (problem 3) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ # BEGIN_YOUR_ANSWER (our solution is 30 lines of code, but don't worry if you deviate from this) # raise NotImplementedError # remove this line before writing code def value(state, depth, agentIndex, isExpValue): if isExpValue == 1: v = exp_value(state, depth, 1) elif agentIndex == state.getNumAgents()-1 : v = max_value(state, depth+1) else : v = exp_value(state, depth, agentIndex+1) return v def max_value(state, depth): v = -math.inf if depth == self.depth or state.isWin() or state.isLose(): v = self.evaluationFunction(state) else : for action in state.getLegalActions(): v = max(v, value(state.generateSuccessor(0, action), depth, 1, 1)) return v def exp_value(state, depth, agentIndex): v = 0 if depth == self.depth or state.isWin() or state.isLose(): v = self.evaluationFunction(state) else : p = 1/len(state.getLegalActions(agentIndex)) for action in state.getLegalActions(agentIndex): v += p * value(state.generateSuccessor(agentIndex, action), depth, agentIndex, 0) return v move = Directions.STOP v = -math.inf for action in gameState.getLegalActions(): temp = value(gameState.generateSuccessor(0, action), 0, 1, 1) if temp > v : v = temp move = action return move # END_YOUR_ANSWER ###################################################################################### # Problem 4a (extra credit): creating a better evaluation function def betterEvaluationFunction(currentGameState): """ Your extreme, unstoppable evaluation function (problem 4). """ # BEGIN_YOUR_ANSWER (our solution is 60 lines of code, but don't worry if you deviate from this) # raise NotImplementedError # remove this line before writing code foodDistList = list() for foodPos in currentGameState.getFood().asList(): foodDistList.append(manhattanDistance(currentGameState.getPacmanPosition(), foodPos)) capsuleDistList = list() for capsulePos in currentGameState.getCapsules(): capsuleDistList.append(manhattanDistance(currentGameState.getPacmanPosition(), capsulePos)) ghostDistScore = 0 for ghost in currentGameState.getGhostStates(): ghostPos = ghost.configuration.getPosition() ghostDist = manhattanDistance(currentGameState.getPacmanPosition(), ghostPos) if (ghost.scaredTimer > 0) & (ghostDist < 2): if ghostDist == 0 : ghostDistScore += 2.0 else : ghostDistScore += 1.0/(ghostDist) elif (ghost.scaredTimer == 0) & (ghostDist < 2): if ghostDist == 0 : ghostDistScore -= 2.0 else : ghostDistScore -= 1.0/(ghostDist) foodDistMin = math.inf foodDistMinScore = 0 if len(foodDistList) > 0: foodDistMin = min(foodDistList) if foodDistMin < 15: foodDistMinScore = 1.0/(foodDistMin) capsuleDistMin = math.inf capsuleDistMinScore = 0; if len(capsuleDistList) > 0: capsuleDistMin = min(capsuleDistList) if capsuleDistMin < 5: capsuleDistMinScore = 1.0/(capsuleDistMin) eatenFoodNum = 0 for foodPos in currentGameState.getFood().asList(): foodDist = manhattanDistance(currentGameState.getPacmanPosition(), foodPos) if foodDist == 0 : eatenFoodNum += 1 eatenCapsuleNum = 0 for capsulePos in currentGameState.getCapsules(): capsuleDist = manhattanDistance(currentGameState.getPacmanPosition(), capsulePos) if capsuleDist == 0 : eatenCapsuleNum += 1 leftFoodNum = len(currentGameState.getFood().asList()) leftCapsuleNum = len(currentGameState.getCapsules()) features = [foodDistMinScore, capsuleDistMinScore, ghostDistScore, eatenFoodNum, eatenCapsuleNum, leftFoodNum, leftCapsuleNum] weights = [1, 500, 1000, 700, -10, -10, -1] return sum([feature * weight for feature, weight in zip(features, weights)]) # END_YOUR_ANSWER # Abbreviation better = betterEvaluationFunction
""" This program takes in the population census data from (https://www.census.gov/data/tables/time-series/dec/metro-micro/tract-change-00-10.html) in CSV format and writes, the average population percent change for a particular Core Based Statistical Area (CBSA) along with other relevant information, to a CSV file. To run the program use the following command in the terminal python3.8 population.py path/to/input/file/input.csv path/to/output/file/output.csv""" # import statements import sys # Beginning of the program if __name__ == '__main__': # Creating a variable to read the input csv file input_param = sys.argv[1] with open(input_param, 'r') as data: # Creating a dictionary to keep track of the CBSA data_dict = {} # Ignoring the header of the csv file next(data) for i in data: # Splitting each line at the double quote to get three parts of each row in data # because the CSBA title contains a comma. # First Part: data columns before the CSBA title # Second Part: the CSBA title column # Third Part: data columns after CSBA title record = i.rstrip().split("\"") # Observation: The absence of CSBA data creates records of length 1 # The presence of CSBA data creates records of length 3 if len(record) == 3: # Splitting the First Part at commas to get necessary columns starting = record[0].split(",") # Splitting the First Part at commas to get necessary columns ending = record[2].split(",") # If there is no CSBA code in the dictionary we add it to the dictionary with the following columns # CSBA code, CSBA title, GEO code to count the instances, Population in 2000, Population in 2010 # Percent change in population # The key of the dictionary is CSBA code and the value is a list containing the above columns in that # order if data_dict.get(starting[7], None) is None: # In case the population change is zero we read an "(X)" # then we add a zero to out list if ending[9] != "(X)": data_dict[starting[7]] = [int(starting[7]), record[1], [starting[0]], int(ending[4]), int(ending[6]), float(ending[9])] else: data_dict[starting[7]] = [int(starting[7]), record[1], [starting[0]], int(ending[4]), int(ending[6]), 0] # In case we already have the CSBA code in our dictionary we add the following # GEO code, Population in 2000, Population in 2010 and Percent change in population else: data_dict[starting[7]][2].append(starting[0]) data_dict[starting[7]][3] += int(ending[4]) data_dict[starting[7]][4] += int(ending[6]) if ending[9] != "(X)": data_dict[starting[7]][5] += float(ending[9]) else: data_dict[starting[7]][5] += 0 # Closing the data file after reading all the records data.close() # Modifying the data to create desired output with average population percent change for item in data_dict: data_dict[item][2] = len(set(data_dict[item][2])) data_dict[item][5] = round(data_dict[item][5] / data_dict[item][2], 2) data_dict[item][1] = "\""+data_dict[item][1]+"\"" # Creating a list of lists from the dictionary to sort the data unsorted_records = [] for element in data_dict: unsorted_records.append(data_dict[element]) # Sorting the data based on the CSBA code in ascending order sorted_records = sorted(unsorted_records, key=lambda x: x[0]) # print(sorted_records) output_param = sys.argv[2] # Using the second parameter to create an output csv file file = open(output_param,'w+') for row in sorted_records: file.write("{},{},{},{},{},{}\n".format(row[0], row[1], row[2], row[3], row[4], row[5])) # Closing the file after the completion of usage file.close()
#!/usr/bin/env python class Solution(object): def trap(self, height): """ :type height: list of int :rtype: int """ water = 0 height_len = len(height) if height_len < 3: return water max_level = max(height) max_level_index = height.index(max_level) prev_level = height[0] for x in range(max_level_index): level = height[x] if level < prev_level and level < max_level: water += (prev_level - level) else: prev_level = level prev_level = height[-1] for x in range(height_len-1, max_level_index, -1): level = height[x] if level < prev_level and level < max_level: water += (prev_level - level) else: prev_level = level return water if __name__ == '__main__': s = Solution() height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] print s.trap(height)
# Capturando dados do terminal - Input nome = input('Digite seu nome: ') print('O nome digitado foi:', nome) # conversao de sring para int (cast) idade = int(input(nome + ' digite sua idade: ')) print('A idade digitada foi:', idade)
# Curso: Python Fundamentos Proway # Aula : Dia 2 - Parte 3 # Assunto: Dicionários # Data: 2021-08-28 #bebidas = lista = ['maykon'] tuplas = ('maykon') lista[0] tuplas[0] # Criando um dicionario dicionario = {'nome':'maykon', 'sobrenome':'granemann', 'idade':10} # Lendo dados de um dicionario print(dicionario['nome']) print(dicionario['sobrenome']) print(dicionario['idade']) # Alterando dados de um dicionario dicionario['nome'] = 'Joana' dicionario['sobrenome'] = 'Nascimento' dicionario['idade'] = 22 # Lendo os dados alterados print(dicionario['nome']) print(dicionario['sobrenome']) print(dicionario['idade']) # adicionando um novo conjunto d chave:valor dicionario['cpf'] = '0555545646' print(dicionario['cpf']) cliente = {} cliente2 = {'nome':'', 'sobrenome':'', 'idade':0} cliente['nome'] = input('digite o nome: ') cliente['sobrenome'] = input('digite o sobrenome: ') cliente['idade'] = int(input('digite a idade: ')) print(cliente) # Deletando uma chave de um dicionario del(cliente['idade']) print(cliente) cliente2['nome'] = input('digite o nome: ') cliente2['sobrenome'] = input('digite o sobrenome: ') cliente2['idade'] = int(input('digite a idade: ')) clientes = [cliente, cliente2] print(clientes)
#coding:utf-8 import matplotlib.pyplot as plt import numpy as np from sklearn.pipeline import Pipeline from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn import linear_model # 数据生成 x = np.arange(0,1,0.002) y = np.random.randn(500,)/10 y = y + x**2 # 均方差根 def rmse(y_test,y): return np.sqrt(np.mean((y_test - y) ** 2)) # 与均值相比的优秀程度,介于[0~1]。0表示不如均值,1表示完美预测 def R2(y_test,y_true): return 1 - ((y_test - y_true) ** 2).sum() / ((y_true - y_true.mean()) ** 2).sum() # conway&white《机器学习使用案例解析》里的版本 def R22(y_test,y_true): y_mean = np.array(y_true) y_mean[:] = y_mean.mean() return 1 - rmse(y_test,y_true)/rmse(y_mean,y_true) plt.scatter(x,y,s = 5) degree = [1,2,100] y_test = [] y_test = np.array(y_test) for d in degree: clf = Pipeline([('poly', PolynomialFeatures(degree=d)), ('linear', LinearRegression(fit_intercept=False))]) clf.fit(x[:, np.newaxis], y) y_test = clf.predict(x[:,np.newaxis]) print (clf.named_steps['linear'].coef_) print('rmse=%.2f, R2=%.2f, R22=%.2f, clf.score=%.2f' %(rmse(y_test, y),R2(y_test, y),R22(y_test, y),clf.score(x[:, np.newaxis], y))) plt.plot(x, y_test, linewidth=2) plt.grid() plt.legend(['1','2','100'], loc='upper left') plt.show()
#from goto import goto, comefrom, label # -*- coding: utf-8 -*- import os import time has1stkey = 0 questmaterials = 0 hascasefile = 0 print print "Noir Clue" print print raw_input("It was a dark and stormy night. [Enter]") print raw_input("Well, actually it was only sprinkling, and it was closer to dawn than anything else, but it was a dark dawn, made even darker by the events transpiring just as the sun peaked over the horizon. [Enter]") print print "*Crash!*" print "*Scream!*" print raw_input("U.I.P: Oh my god, Francis! Someone please help, oh lord! [Enter]") print print raw_input("Commissioner: We aren't certain about what it could be yet, the cause of death just doesn’t seem natural, but it doesn't line up with anything we know about. We don't really have the time to look around, which is where you come into I guess... Just poke around a bit, we'll get back to you as soon we have some concrete test results. Oh, and please give my condolences to Harriet, Francis... Francis was a good man... Good Luck. [Enter]") print print raw_input("Your name is Clinton Weatherbee and you've been assigned your first investigation as a hired investigator. Granted it's a pretty open and shut case from where you're standing, but it's still yours, and you're going to do the best job you can, right down to the paper work. [Enter]") print raw_input("All paperwork aside, you are currently standing on a muddy pathway leading up to a... 'cozy' or 'ramshackle' ranch house. It's a faint echo of what was likely a crown jewel of one of the many families that lost their wealth in the Downslide one or two decades back. Now it's fallen to disrepair, paint thinning and peeling from the recent rainshowers, shingles falling off the roof, and what seems to be mold growing in the walls. [Enter]") def FirstOption(): print raw_input("In the front of the house there stands Harriet, spouse of the victim. She's discussing the accident with several 'real' policemen. The whole reason why you and your firm were hired was because those bulls couldn't give enough of a damn about it. The commissioner is only pulling an investigation as a favor to the victim. Let's show them how we do it. [Enter]") print "Search Grounds" print "Question Police" print "Question Harriet" print "Enter House" print FirstOption() QuestStart = raw_input(": ") while QuestStart != "Search Grounds" or QuestStart != "Question Police" or QuestStart != "Question Harriet" or QuestStart != "Enter House": QuestStart = raw_input("(Type an actual answer please): ") if QuestStart == "Search Grounds" or QuestStart == "Question Police" or QuestStart == "Question Harriet" or QuestStart == "Enter House": break if QuestStart == "Search Grounds": print "You ignore the people and decide to search the area around the house." print print "If nature was waging war against humanity then this is the front lines. The yard is covered in unkempt grass and is bordered by overgrown bushes. At the side of the house there’s a door… thingy… but on the ground, kinda like the one Dorthy hid in in the wizard of oz, wait no, tried to hid in cause… whatever, it’s a basement door but on the ground. What do you want to look at first?" print print "Ground Door" print "Grass" print "Bushes" print "Turn Back" SidePath1 = raw_input(": ") while SidePath1 != "Ground Door" or SidePath1 != "Grass" or SidePath1 != "Bushes" or SidePath1 != "Turn Back": SidePath1 = raw_input("(Type an actual answer please): ") if SidePath1 == "Ground Door" or SidePath1 == "Grass" or SidePath1 == "Bushes" or SidePath1 == "Turn Back": break if SidePath1 == "Ground Door": if has1stkey == 1: print raw_input("As you walk over you just remembered that it's called a cellar. Anyway you wander over to the Cellar Door and remember the key you found earlier. [Enter]") print raw_input("You take the key out of your pocket and shove it in the lock, it clicks open and you open the door and look down at the stairs leading to the cellar. [Enter]") print raw_input("OH GOD WHAT IS THAT?? AAAAAAAAAAAAHHHH! Hah ha, just kidding, it's too dark to see anything here. You should probably find some sort of flashlight or candle before you do anything else, like walk into a dark room and trip over something. [Enter]") EndSide1 = raw_input("Type 'Return' to go back: ") if EndSide1 == "Return": print FirstOption() QuestStart = raw_input(": ") if has1stkey == 0: print "As you walk over you just remembered that it's called a cellar. Anyway you wander over to the Cellar Door, but upon closer examination you find that it's locked. Well, shit. What a waste of a command prompt. There's gotta be a key somewhere though. *HINT. HINT*" EndSide1 = raw_input("Type 'Return' to go back: ") if EndSide1 == "Return": print FirstOption() QuestStart = raw_input(": ") elif SidePath1 == "Bushes": print "After a couple of cuts and bruises you come up with… A Plastic Bag! Amazing" print raw_input("After rummaging around for awhile you find… Absolutely nothing. Great.") print "On your way back from the bushes you find a quarter. Score!" EndSide1 = raw_input("Type 'Return' to go back: ") if EndSide1 == "Return": print FirstOption() QuestStart = raw_input(": ") elif SidePath1 == "Grass": print "You look through the grass and find a key! Hopefully it unlocks something nearby, for what's a key without a lock? A cigar without a wealthy man behind it? A cat without a saucer of cream? Something like that." has1stkey = 1 questmaterials = 1 print "Small Key added to the Inventory" EndSide1 = raw_input("Type 'Return' to go back: ") if EndSide1 == "Return": print FirstOption() QuestStart = raw_input(": ") elif SidePath1 == "Turn Back": print FirstOption() QuestStart = raw_input(": ") else: SidePath1 = raw_input(": ") elif QuestStart == "Question Police": print "There are two policeman, fat-heads... they’re talking about the Case." print raw_input("You pretend to be writing something as the police discuss. [Enter]") print raw_input("P1: So then I pour the egg and vegetable mix into the fry pan and saute for about... [Enter]") print raw_input("P2: You know I love you're cooking, and breakfast foods, but I have to ask, what does this have to do with the case? [Enter]") print raw_input("P1: Oh, yeah, well there's a cast iron skillet in the kitchen and you know how I love those so I got thinking and... [Enter]") print raw_input("P2: ...and we should really just compare notes [Enter]") print raw_input("P1: You for it. None of the people on the grounds seem to have anything to tell us. Some give off some weird vibes, but hey, who doesn't after a death. What about you? [Enter]") print raw_input("P2: I couldn't find anything of note around here. Might be something in the cellar, I couldn't get in. Probably not though, I looked through the window and only saw some fruit preserves. Gotta keep busy somehow, eh? I can't imagine being in this property all alone, makes sense why he took so many folks in. Anyway I saw one... Hey! [Enter]") print "Oh shit oh crap oh shit" print raw_input("P2: You're the hired P.I. right? We'll be going pretty soon but if you need any advice we can share what we have. [Enter]") if questmaterials >= 1: print raw_input("P1: Hey P.I., you wanna compare notes? [Enter]") if has1stkey == 1: print "P1: A key without a lock is like a man without a dame, not the reason why we became police officers." EndSide1 = raw_input("Type 'Return' to go back: ") if EndSide1 == "Return": print FirstOption() QuestStart = raw_input(": ") elif QuestStart == "Question Harriet": raw_input("Harriet looks visibly shaken, he was the one who discovered the body only six hours ago after all. [Enter]") print "Harriet: Oh, you're the private detective right? Good morning Sir." print "Still very polite though." raw_input("What do you want to ask? [Enter]") def SideOptions(): askedHarall = 0 SP2options = {"Possible Motive", "Discovery of Body", "How He's Getting Along"} print SP2options SidePath2 = raw_input(": ") if SidePath2 == "Possible Motive": raw_input("Harriet: I wouldn't really know. Francis never made any enemies and I can't really imagine anyone hating him enough to kill him. [Enter]") askedHarall += 1 SP2options.append("Why do you think it was a murder?") SideOptions() SidePath2 = raw_input(": ") elif SidePath2 == "Why do you think it was a murder?": print "Harriet looks insulted" raw_input("Harriet: Did you even read the Case File? He had three direct wounds to the chest, that doesn't happen naturally. [Enter]") print "You remember that you do, indeed, have the Case File on you." hascasefile = 1 questmaterials = 1 print "Case File added to the Inventory" askedHarall += 1 SideOptions() SidePath2 = raw_input(": ") elif SidePath2 == "Discovery of Body": print "Harriet: I came downstairs around 5 am this morning, I entered the kitchen looking for Francis, by then... he was already dead. I didn't see anything, but the window was broken." askedHarall += 1 SideOptions() SidePath2 = raw_input(": ") elif SidePath2 == "How She's Getting Along": raw_input("Harriet: The house has always been pretty empty due to Francis being gone so often, but now it's just... echoes. [Enter]") print "Well... that's depressing." askedHarall += 1 if askedHarall == 4: raw_input("There's nothing else you can ask right now. [Enter]") else: SideOptions() SidePath2 = raw_input(": ") raw_input("Harriet: You're free to go through the house, it's a bit of a mess, it's not like I was expecting people to show up. Please don't harrass my house guests though, they've been through enough already. [Enter]") elif QuestStart == "Enter House": if askedHarall >= 1: raw_input("You enter the house, there's a stairway going up, and a door right below the second floor landing, an entryway to the living room on the right, and to the left there is A PIT TO HELL [Enter]") FirstHouseOptions = {"Stairway", "Door", "Living Room", "HELL PIT", "Leave"} HousePath1 = raw_input(: ) if HousePath1 == "HELL PIT": print "You enter Hell, it's empty, all the sinners must be elsewhere, you walk to the hell castle and sit on the throne, congrats, you now rule hell." print "(GAME OVER)" print "Ending: The American Dream" if HousePath1 == "Leave": print "You just… leave, not just the house but the entire area, you just straight up start walking. Fuck being a private investigator, fuck everything. You live the rest of your life on a farm, you find someone you love and you settle down and have two kids, you forget the investigation and your life as a private investigator, but somehow, you’re happy… Until aliens take over your planet of course." print "(GAME OVER)" print "Ending: This Ain't Signs" if HousePath1 == "Door": raw_input("You go through the door. [Enter]") if HousePath1 == "Living Room": raw_input("You walk into the living room. [Enter]") elif askedHarall == 0: print "Harriet: Just who are you?" SideOptions() SidePath2 = raw_input(": ") else: QuestStart = raw_input(": ")
# Brandon Coats # CTI 110 # M6T2_FeetToInches # Solves feet to inches. INCHES_PER_FOOT = 12 def main(): feet = int(input('Enter a number of feet: ')) print(feet,'equals', feet_to_inches(feet), 'inches.') def feet_to_inches(feet): return feet * INCHES_PER_FOOT main()
class QuickSort: def partition(self, array, low, high): pivot = array[low] i = low + 1 j = high while True: while i <= j and array[j] >= pivot: j -= 1 while i <= j and array[i] <= pivot: i += 1 if i <= j: array[i], array[j] = array[j], array[i] else: break array[low], array[j] = array[j], array[low] return j def sort(self, array, low, high): if low >= high: return p = self.partition(array, low, high) self.sort(array, low, p-1) self.sort(array, p+1, high) if __name__ == "__main__": array = [6, 4, 42, 32, 1, 7, 13, 12, 3, 44, 2, 6, 78, 54] quick = QuickSort() quick.sort(array, 0, len(array) - 1) print(array)
import re def preprocess(s,display): operand=re.findall(r'\d+',s) operator=re.findall(r'[^\d ]',s) if len(operand)>2 or len(operator)>1: return "Error: Numbers must only contain digits." if len(operand[0])>4 or len(operand[1])>4: return "Error: Numbers cannot be more than four digits." if not (operator[0] in ('-','+') ): return "Error: Operator must be '+' or '-'." maxlen=max(len(operand[0]),len(operand[1])) block=[operand[0].rjust(maxlen+2),operator[0]+' '+operand[1].rjust(maxlen),'-'*(maxlen+2)] if display: if operator[0]=='-': block.append(str(int(operand[0])-int(operand[1])).rjust(maxlen+2)) if operator[0]=='+': block.append(str(int(operand[0])+int(operand[1])).rjust(maxlen+2)) return block def arithmetic_arranger(problems,display=False): if len(problems)>5 : return "Error: Too many problems." seperator=' '*4 blocks=[] for s in problems: blocks.append(preprocess(s,display)) if type(blocks[-1])==str: return blocks[-1] arranged_problems='' if display==True: count=4 else: count=3 for i in range(count): for j in blocks: arranged_problems+=j[i]+seperator if j==blocks[-1]: arranged_problems=arranged_problems[0:-4] arranged_problems+='\n' return arranged_problems[0:-1]
def isAnagram(s1,s2): s1 = s1.replace(" ","").lower() s2 = s2.replace(" ","").lower() hm = dict() for s in s1: if s in hm: hm[s] += 1 else: hm[s] = 1 for s in s2: if s in hm: hm[s] -= 1 else: hm[s] = 1 for i in hm: if hm[i] != 0: return False return True s1 = "fairy tales" s2 = "rail safety" print(isAnagram(s1,s2))
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None def append(self, data): newNode = Node(data) if self.head is None: self.head = newNode self.head.next = self.head else: curr = self.head while curr.next and curr.next != self.head: curr = curr.next curr.next = newNode curr.next.next = self.head def prepend(self, data): newNode = Node(data) if self.head is None: self.head = newNode self.head.next = self.head else: curr = self.head while curr.next and curr.next != self.head: curr = curr.next curr.next = newNode newNode.next = self.head self.head = newNode def remove_node(self, data): if self.head.next == self.head and self.head.data == data: self.head = None return prev = None curr = self.head while curr: if curr.data == data: if prev: next = curr.next prev.next = next else: current = self.head while current.next and current.next != self.head: current = current.next next = self.head.next current.next = next self.head = next break prev = curr curr = curr.next if curr == self.head: break def split_list(self): len = 1 curr = self.head while curr.next != self.head: curr = curr.next len += 1 tail = curr split = len // 2 count = 1 curr = self.head while count != split: curr = curr.next count += 1 next = curr.next curr.next = self.head # second list tail.next = None splitList = CircularLinkedList() while next: splitList.append(next.data) next = next.next self.printList() print("\n") splitList.printList() def printList(self): curr = self.head while curr: print(curr.data) curr = curr.next if curr == self.head: break Cll = CircularLinkedList() Cll.prepend(1) Cll.append(2) Cll.append(3) Cll.append(4) Cll.append(5) Cll.append(5) Cll.split_list()
class MyClass: def __init__(self, x, y): self.x = y self.y = x obj1 = MyClass(2, 5) print('x =', obj1.x) print('y =', obj1.y)
handle = open("Writing_Files/test.txt","w") handle.write("This is just a test") handle.close() handle = open("Writing_Files/test.txt","r") while True: data = handle.read(1024) print(data) if not data: break print('-------------------------------------------------------------------') # Python has a neat little builtin called with which you can use to simplify reading # and writing files. The with operator creates what is known as a context manager in Python # that will automatically close the file for you when you are done processing it with open("Writing_Files/test.txt") as file_handler: for line in file_handler: print(line)
from LinkedList import LinkedList def nth_to_the_last_node(list, n): length = list.length() if n <= length: n = length - n count = 0 cur = list.head while cur: if count == n: return cur.data count += 1 cur = cur.next return def nth_to_the_last_node_2(list, n): p = list.head q = list.head count = 1 while p: if count >= n: break count += 1 p = p.next while p.next and q: p = p.next q = q.next return q.data llist = LinkedList() llist.append("A") llist.append("B") llist.append("C") llist.append("D") print(nth_to_the_last_node(llist,4)) print(nth_to_the_last_node_2(llist,4))
import datetime class Schedule: def __init__(self, start, end, name, other): # Constructor self.start = self.str_convert(start) # Schedule start time (ex. 9:00) self.end = self.str_convert(end) # Schedule end time (ex. 22:00) self.name = name # Schedule name (ex. member name, final schedule, etc) self.other = other # Schedule exceptions/"other" self.array = self.create_array() # Schedule array (2D array of days of week (7) x half hour blocks) def str_convert(self, str_time): # Converts start/end time to datettime if entered as string if isinstance(str_time, str): str_time = datetime.datetime.strptime(str_time, '%H:%M') return datetime.time(str_time.hour, str_time.minute) return str_time def create_array(self): # Generate array from number of (30 minute) blocks num_blocks = self.calculate_num_blocks(self.start, self.end) return [[True for x in range(num_blocks)] for y in range(7)] @staticmethod def calculate_num_blocks(start, end): # Determining size of array: get difference total_hrs = end.hour - start.hour total_mins = end.minute - start.minute # Determining size of array: in 30 min blocks (rounded) num_half_hr = int(total_mins/30) num_blocks = 2 * total_hrs + num_half_hr return num_blocks # def get_time def prep_visualize(self): # Banner print("\n######### VISUALIZING WEEK: " + self.name + " #########") print(self.start, "-", self.end, "\n") num_blocks = self.calculate_num_blocks(self.start, self.end) days = ["S", "M", "T", "W", "R", "F", "S" ] times = [] # Fill times column (from datetime obj) # Convert to datetime.datetime object, add timedelta, convert back - arbitrary datetime.date(1, 1, 1) dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start) for i in range(num_blocks): num_blocks_i = datetime.timedelta(minutes=30*i) combined = (dtdt + num_blocks_i).time() times.append(combined.strftime("%H:%M")) return days, times def visualize(self): days, times = self.prep_visualize() # HEADER: print("#####", end=" ") for d in days: print("(" + d + ") ", end="") print("#####") # SCHEDULE: for t in range(len(times)): print(times[t], end=" ") for d in range(7): slot = self.array[d][t] if slot is True: slot = " " elif slot is False: slot = " x " print(slot, end=" ") print(times[t]) print() def print_other(self): print(self.name + "\t ", self.other.replace("\n", "; ")) class ExSchedule(Schedule): def __init__(self, start, end, num_members, list_membs): Schedule.__init__(self, start, end, "ExSched", None) self.num_members = num_members self.list_membs = list_membs self.exarray = self.create_exarray() def create_exarray(self): num_blocks = Schedule.calculate_num_blocks(self.start, self.end) return [[[True for z in range(self.num_members)] for x in range(num_blocks)] for y in range(7)] def visualize(self): days, times = Schedule.prep_visualize(self) print("Members: "+ self.list_membs[:-2]) # HEADER: print("##### ", end="") # print(days) # print(times) for d in days: num_spaces = len(self.exarray[0][1]) - 1 left_half = int(num_spaces / 2) right_half = num_spaces - left_half print("(", end="") print(''.join([" " for x in range(left_half)]), end=d) print(''.join([" " for x in range(right_half)]), end=")") print(" #####") # SCHEDULE: for i in range(len(times)): # i: 0-26 (9:00) = m: 0-26 ([T,T,T]) print(times[i], end=" ") for d in range(len(self.exarray)): # d: 0-6 (sun) array = self.exarray[d][i] print("[", end="") for memb_avail in array: print("-", end="") if memb_avail is True else print("*", end="") print("]", end="") print(" ", end=times[i]+"\n")
# Polyalphabetic cipher- Vigenere Cipher # Uses multiple Caesar ciphers to shift each letter in input based on the key # References: https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher # Limitations: converts all characters to lowercase, can be changed, just how I set it up def vigEncrypt(input, key): keyLength = len(key) keyInt = [ord(i) for i in key] inputInt = [ord(i) for i in input] output = '' for char in range(len(inputInt)): if inputInt[char] == 32: output += " " else: ciphernum = (inputInt[char] + keyInt[char % keyLength]) % 26 cipherchar = chr(ciphernum + 65).lower() output += cipherchar return (output) def vigDecrypt(input, key): keyLength = len(key) keyInt = [ord(i) for i in key] inputInt = [ord(i) for i in input] output = '' for char in range(len(inputInt)): if inputInt[char] == 32: output += " " else: ciphernum = (inputInt[char] - keyInt[char % keyLength]) % 26 cipherchar = chr(ciphernum + 65).lower() output += cipherchar return (output) print (vigEncrypt("ATTACK AT DAWN", "PIZZA")) print (vigDecrypt("PBSZCZ ZS SIVM", "PIZZA"))
# In the 'mimsmind' game, the computer program # will generate a random integer number and prompt the human player to guess the number. # After each guess, the computer will # provide feedback to guide the human in making his/her next guess. # The game will end when the player correctly guesses the number # or when the player runs out of guesses. # We would like you to implement this game in two versions. # You should complete version 0 before starting on version 1. # In this version, the program generates a random number with number of digits equal to length. # If the command line argument length is not provided, the default value is 1. # Then, the program prompts the user to type in a guess, # informing the user of the number of digits expected. # The program will then read the user input, and provide basic feedback to the user. # If the guess is correct, # the program will print a congratulatory message with the number of guesses made and terminate the game. # Otherwise, the program will print a message asking the user to guess a higher or lower number, # and prompt the user to type in the next guess. import random def number_guessing(): print("Let's play the mimsmind0 game.") answer = input("Please enter the digit of number you are interested in guessing: ") if answer == "": answer = 1 else: answer = int(answer) # to finalize the digit using from user input random_interger = random.randint(1, (10 ** answer)+1) count = 0 while True: count += 1 user_guess = int(input("Please take guess a {} digit numer: ".format(answer))) if user_guess == random_interger: print("Congratulations. You guessed the correct number in {} times.".format(count)) break elif user_guess < random_interger: print("Try again. Guess a higher number:") else: print("Try again. Guess a lower number:") # not sure how to do infinite count during the try and error. # I'm thinking to intialize a var = 0. # As the counts cotinue += var # Add to Congrats ... with the .format() # but not sure how to add up def main(): number_guessing() if __name__ == '__main__': main()
#coding: utf-8 a=[] cant=input("Cuantas palabras tendrá la lista?") for i in range(1,cant+1): aux=raw_input("Dígame la palabra "+str(i)+":") a.append(aux) print "La lista creada es: ",a aux=raw_input("Sustituir la palabra:") aux2=raw_input("Por la palabra:") count=a.count(aux) for b in range(count): p=a.index(aux) a[p]=aux2 print "La lista ahora es:",a
import cv2 img = cv2.imread("1.png") font = cv2.FONT_HERSHEY_PLAIN cv2.line(img, (100, 50), (300, 400), (0, 0, 255), 5) # draws a line, positions are (x, y), color is bgr -> (image matrix, start pos, end pos, color, width) cv2.rectangle(img, (200, 500), (800, 900), (0, 132, 195), 10) # draws a rectangle, positions are (x, y), color is bgr -> (image matrix, up left pos, down right pos, color, width) cv2.circle(img, (400, 600), 400, (0, 255, 0), 3) # draws a circle cv2.ellipse(img, (300, 300), (400, 200) , 10, 45, 275, (0, 255, 0), 10) # draws an ellipse (image matrix, center, (width, height) , angle, start angle, end angle, color, thickness) cv2.putText(img, "Detected", (250, 220), font, 10, (0, 255, 0), 5) # writes something -> (image matrix, text, start pos, font, size, color, thickness) cv2.imshow("image window", img) cv2.waitKey(0) cv2.destroyAllWindows()
"""класс куча""" class queue(): def __init__(self, arr, mod): """ def __init__(self, arr, mod) arr - массив из которого будет построена куча mod - строка "min" или "max" в зависимости от этого параметра будет построена куча по минимуму или максимуму соответственно """ if mod == "min": mod = lambda x, y: x < y else: mod = lambda x, y: x > y self.arr = arr self.mod = mod self.queue = [0] # первый элемент содержит длину кучи self.makeheap() def makeheap(): for element in self.arr: self.insert(element) def insert(element): self.len += 1 self.queue.append(element) ind = self.len while ind and
#Fucntion to read from a c++ style file.dat def read_from_file(name): """Function to read from a file called name it return a matrix of the various numbers""" f= open(name,'r') lines=f.readlines() lines2=[x.replace("\t"," ") for x in lines] lines3=[x.replace("\n","") for x in lines2] result=[[float(x) for x in res.split()] for res in lines3] return result
import random import matplotlib.pyplot as plt heads = 0 tails = 0 iterations = 0 results = [] def askUserHowManyFlips(): amountOfFlips = int(input("How many flips?:")) return amountOfFlips def flip(flips): global heads, tails, iterations for i in range(flips): flip = random.randrange(2) results.append(flip) if flip == 0: heads += 1 iterations += 1 elif flip == 1: tails += 1 iterations += 1 def calculateTheAverage(): sumOfValues = sum(results) average = sumOfValues / len(results) return f"The average was {average}, 0 being heads and 1 being tails" def theDifference(): if heads > tails: difference = heads - tails statement = f"There were {difference} more heads than tails" elif tails > heads: difference = tails - heads statement = f"There were {difference} more tails than heads" return statement def winner(): if heads > tails: winner = "heads" elif tails > heads: winner = "tails" return f"{winner} wins!" def percentage(): global heads, tails percentage_heads = str(heads / iterations * 100) + '%' percentage_tails = str(heads / iterations * 100) + '%' return f"heads was flipped {percentage_heads} of the time, tails was flipped {percentage_tails} of the time" def plot(): global heads, tails labels = "heads", "tails" sizes = [heads, tails] colors = ['red', 'yellow'] if heads > tails: explode = [0.5, 0] elif tails > heads: explode = [0, 0.5] plt.pie(sizes, explode=explode, labels=labels, colors=colors, shadow = True) plt.axis('equal') plt.show() def run(): amountOfFlips = askUserHowManyFlips() flip(amountOfFlips) print(calculateTheAverage()) print(f"{heads} heads and {tails} tails") print(theDifference()) print(percentage()) print(winner()) plot() run()
#!/usr/bin/python import sys import re import copy import random assert len(sys.argv) == 2, sys.argv[0] + " requires 1 argument!" class Player: def __init__(self, damage, armor, cost): self.damage = damage self.armor = armor self.hp = 100 self.cost = cost def printMe(self): print "{}: {} {} {}".format(self.cost, self.damage, self.armor, self.hp) def isDead(self): return self.hp <= 0 def attacked(self, damage): self.hp -= max(1, (damage - self.armor)) #print "The boss deals {}-{} = damage, player at {} hp".format(damage, self.armor, self.hp) class Boss: def __init__(self, hp, damage, armor): self.damage = damage self.armor = armor self.hp = hp def printMe(self): print "boss: {} {} {}".format(self.damage, self.armor, self.hp) def isDead(self): return self.hp <= 0 def attacked(self, damage): self.hp -= max(1, (damage - self.armor)) #print "The player deals {}-{} = damage, boss at {} hp".format(damage, self.armor, self.hp) inputFile = open(sys.argv[1], "r") for line in inputFile.readlines(): hp = re.match("^Hit Points: (\d+)", line) d = re.match("^Damage: (\d+)", line) a = re.match("^Armor: (\d+)", line) if hp: bossHP = int(hp.group(1)) if d: bossDamage = int(d.group(1)) if a: bossArmor = int(a.group(1)) inputFile.close() # gold, damage weapons = {} weapons["Dagger"] = ( 8, 4) weapons["Shortsword"] = (10, 5) weapons["Warhammer"] = (25, 6) weapons["Longsword"] = (40, 7) weapons["Greataxe"] = (74, 8) # gold, armor armor = {} armor["None"] = ( 0, 0) armor["Leather"] = ( 13, 1) armor["Chainmail "] = ( 31, 2) armor["Splintmail"] = ( 53, 3) armor["Bandedmail"] = ( 75, 4) armor["Platemail"] = (102, 5) # gold, damage, armor rings = {} rings["Damage 1"] = ( 25, 1, 0) rings["Damage 2"] = ( 50, 2, 0) rings["Damage 3"] = (100, 3, 0) rings["Defense 1"] = ( 20, 0, 1) rings["Defense 2"] = ( 40, 0, 2) rings["Defense 3"] = ( 80, 0, 3) # generate all player combos players = [] for w in weapons.keys(): for a in armor.keys(): # no rings dVal1 = weapons[w][1] aVal1 = armor[a][1] cost1 = weapons[w][0] + armor[a][0] players.append(Player(dVal1, aVal1, cost1)) #print "{}: {} {}".format(cost1, w, a) # 1 ring ringList = rings.keys() for idx,r in enumerate(ringList): dVal2 = dVal1 + rings[r][1] aVal2 = aVal1 + rings[r][2] cost2 = cost1 + rings[r][0] players.append(Player(dVal2, aVal2, cost2)) #print "{}: {} {} {}".format(cost2, w, a, r) # 2 rings for r2 in ringList[idx+1:]: dVal3 = dVal2 + rings[r2][1] aVal3 = aVal2 + rings[r2][2] cost3 = cost2 + rings[r2][0] players.append(Player(dVal3, aVal3, cost3)) #print "{}: {} {} {} {}".format(cost3, w, a, r, r2) players.sort(key=lambda c: c.cost) for p in players: #print "----------------" boss = Boss(bossHP, bossDamage, bossArmor) while not (p.isDead() or boss.isDead()): boss.attacked(p.damage) if not boss.isDead(): p.attacked(boss.damage) if not p.isDead(): lowestCost = p.cost break print "=============" print "=== Part 1" print "Min Gold = {}".format(lowestCost) print "=============" players.sort(key=lambda c: c.cost, reverse=True) for p in players: #print "----------------" boss = Boss(bossHP, bossDamage, bossArmor) while not (p.isDead() or boss.isDead()): boss.attacked(p.damage) if not boss.isDead(): p.attacked(boss.damage) if p.isDead(): maxCost = p.cost break print "=============" print "=== Part 1" print "Max Gold = {}".format(maxCost) print "============="
class Vector: def __init__(self, values): self.values = values @staticmethod def itol(value): i = 0 ret = [] while i < value: ret.append(float(i)) i += 1 return ret @staticmethod def ttol(value): ret = [] for i in range(value[0], value[1]): ret.append(float(i)) return ret @staticmethod def is_float_list(value): for nbr in value: if not(isinstance(nbr, float)): return False return True @property def values(self): return self._values @property def size(self): return len(self._values) @values.setter def values(self, value): try: if not value: raise ValueError elif isinstance(value, int): self._values = self.itol(value) elif isinstance(value, tuple): self._values = self.ttol(value) elif isinstance(value, list): if not(self.is_float_list(value)): raise TypeError self._values = value else: raise TypeError except ValueError: print("Error:\nNo argument found") except TypeError: print("Error:\n\ You should be able to initialize the object with:\n\ • a list of floats: Vector([0.0, 1.0, 2.0, 3.0])\n\ • a size Vector(3) -> the vector will have values = [0.0, 1.0, 2.0]\n\ • a range or Vector((10,15)) -> the vector will have values = [10.0, 11.0, \ 12.0, 13.0, 14.0]\ ") def __str__(self): txt = f"Vector {self.values}" return txt def __add__(self, other): ret = [] try: if not(isinstance(other, (Vector, int, float))): raise TypeError elif isinstance(other, Vector): if self.size != other.size: raise ValueError for i in range(0, self.size): ret.append(self.values[i] + other.values[i]) else: for t in range(0, self.size): ret.append(self.values[t] + other) except TypeError: print("Error:\nVector instance can only be sum with another \ Vector instance or with a scalar(int, float)") except ValueError: print("Error:\nVector instance can only be sum with the same \ dimension") return ret def __radd__(self, other): ret = [] try: if not(isinstance(other, (int, float))): raise TypeError else: for t in range(0, self.size): ret.append(self.values[t] + other) except TypeError: print("Error:\nVector instance can only be sum with another \ Vector instance or with a scalar(int, float)") return ret def __sub__(self, other): ret = [] try: if not(isinstance(other, (Vector, int, float))): raise TypeError elif isinstance(other, Vector): if self.size != other.size: raise ValueError for i in range(0, self.size): ret.append(self.values[i] - other.values[i]) else: for t in range(0, self.size): ret.append(self.values[t] - other) except TypeError: print("Error:\nVector instance can only be sub with another \ Vector instance or with a scalar(int, float)") except ValueError: print("Error:\nVector instance can only be sub with the same \ dimension") return ret def __rsub__(self, other): ret = [] try: if not(isinstance(other, (int, float))): raise TypeError else: for t in range(0, self.size): ret.append(self.values[t] - other) except TypeError: print("Error:\nVector instance can only be sub with another \ Vector instance or with a scalar(int, float)") return ret def __truediv__(self, other): ret = [] try: if not(isinstance(other, (int, float))): raise TypeError else: for t in range(0, self.size): ret.append(self.values[t] / other) except TypeError: print("Error:\nVector instance can only be div with a \ scalar(int, float)") return ret def __rtruediv__(self, other): ret = [] try: if not(isinstance(other, (int, float))): raise TypeError else: for t in range(0, self.size): ret.append(self.values[t] / other) except TypeError: print("Error:\nVector instance can only be div with a \ scalar(int, float)") return ret def __mul__(self, other): try: if not(isinstance(other, (Vector, int, float))): raise TypeError elif isinstance(other, Vector): ret = 0 if self.size != other.size: raise ValueError for i in range(0, self.size): ret += self.values[i] * other.values[i] else: ret = [] for t in range(0, self.size): ret.append(self.values[t] * other) except TypeError: print("Error:\nVector instance can only be multiplication \ with another Vector instance or with a scalar(int, float)") except ValueError: print("Error:\nVector instance can only be multiplicated with \ the same dimension") return ret def __rmul__(self, other): ret = [] try: if not(isinstance(other, (int, float))): raise TypeError else: for t in range(0, self.size): ret.append(self.values[t] * other) except TypeError: print("Error:\nVector instance can only be multiplicated with \ another Vector instance or with a scalar(int, float)") return ret
from recipe import Recipe from book import Book livro = Book("teste") print(livro.name) print(livro.creation_date) print(livro.recipes_list) teste = Recipe("wincenty", 5, 20, ["6", "pedra", "vestido"], "starter", "otima refeicao") teste2 = Recipe("outra", 5, 20, ["6", "pedra", "vestido"], "dessert", "otima refeicao") teste3 = Recipe("aquivai", 5, 20, ["6", "pedra", "vestido"], "lunch", "otima refeicao") livro.add_recipe(teste) livro.add_recipe(teste2) livro.add_recipe(teste3) livro.get_recipe_by_name("aquivai") livro.get_recipe_by_name("outra") livro.get_recipe_by_name("wincenty") print("last update: ", livro._last_update) lista = livro.get_recipes_by_types("lunch") for name in lista: print(lista) lista = livro.get_recipes_by_types("dessert") for name in lista: print(lista) lista = livro.get_recipes_by_types("starter") for name in lista: print(lista) notrecipe = "teste" livro.add_recipe(notrecipe) livro.add_recipe() livro.get_recipes_by_types("teste") livro.get_recipe_by_name("teste")
from __future__ import division import time import sys import random from collections import defaultdict import os index = defaultdict(list) def init_words(): global words with open("dictionary.txt") as file: for line in file: word = line.strip().lower() index[len(word)].append(word) def choose_word(difficulty): global words temp_word = str(random.choice(words)) while len(temp_word) != get_word_length(difficulty): temp_word = str(random.choice(words)) return temp_word.lower() def clear_screen(): from sys import platform as _platform if _platform == "linux" or _platform == "linux2": # Linux os.system('clear') elif _platform == "darwin": # Mac OS X os.system('clear') elif _platform == "win32": # Windows os.system('cls') def get_word_length(dif): return { 1: 6, 2: 8, 3: 10, 4: 13, 5: 15 }[dif] def insert_logo(): print """ _____ / ____| WORD | | __ _ _ ___ ___ ___ | | |_ | | | |/ _ \\/ __/ __| | |__| | |_| | __/\\__ \__ \\ \\_____|\\__,_|\\___||___/___/ By Michael Parker \n""" def initialize(): clear_screen() insert_logo() print "Welcome to Word Guess! This game is a simple word guessing game written in Python." print "\nPlease read the readme.txt file before playing so you know the rules!" print "\nDISCLAIMER: The words used in this game are chosen randomly", print "\nfrom the dictionary file named 'dictionary'. It does contain some swear words", print "\nand I apologise if you get one of them, out of thousands of words available." user_ready = raw_input("\nAre you ready?! (y/n): ").lower().strip() if len(user_ready) > 0 and user_ready[0] == "y": lets_go = "Let's go!" print print lets_go + " 3... ", sys.stdout.flush() time.sleep(1) for i in range(2,0, -1): print "\r" + lets_go + " " + str(i) + "... ", sys.stdout.flush() time.sleep(1) clear_screen() insert_logo() return True else: print "\nOK, come back whenever you're ready!" return False def play_round(difficulty): length = int(raw_input("Enter word length: ")) word = random.choice(index[length]) guessed = [] wrong = [] tries = 5 while tries > 0: out = "" for letter in word: if letter in guessed: out = out + letter else: out = out + " _ " if out == word: break print("Guess the word:", out) print(tries, "chances left") guess = raw_input() if guess in guessed or guess in wrong: print("Already guessed", guess) elif guess in word: print("Well Done!") guessed.append(guess) else: print("Nope! Try again!") tries = tries - 1 wrong.append(guess) print() if tries: print("You guessed", word) else: print("You didn't get", word) def play_game(): lives = 3 points = 0 difficulty = 1 should_harden = False increment_lives = 0 while lives > 0: print "Lives: %s\t\tPoints: %s\t\tDifficulty: %s" % (str(lives), str(points), str(difficulty)) if points >= 10000: print "\nSeriously, who are you?! You know all words in English right?!\nCongrats!!!" return else: print won_or_lost = play_round(difficulty) print if won_or_lost[0] is True: print "Nice! You got it right!" if difficulty < 5: difficulty += should_harden should_harden = not should_harden increment_lives += 1 points += won_or_lost[2] * 100 else: print "I see you couldn't get that one?!\nThe right answer was \"" + won_or_lost[1] + '"!' lives -= 1 sys.stdout.flush() time.sleep(3) if increment_lives == 3: lives += 1 increment_lives = 0 clear_screen() insert_logo() def main(): ready_to_play = initialize() if ready_to_play is True: play_game() play_again = raw_input("\nPlay again? (y/n): ").lower().strip() if len(play_again) > 0 and play_again[0] == "y": main() else: print "\nThanks for playing Word Guess! See you again soon!\n" init_words() main()
from os import system from time import sleep def clear(): system('clear') def add(x, y): return x + y def sub(x, y): return x - y def mul(x, y): return x * y def div(x, y): if(y == 0): print ("Division by ZERO!!!") return None return x / y def mathFunc(func, x, y): print("Answer is: " + str(func(int(x),int(y)))) cnt = True while cnt: clear() oper = input(""" What is your operation Addition Subtraction Multiplication Division Quit PLEASE ENTER (+, -, *, /, q): """) clear() if(oper == '+'): print ("Addition") mathFunc(add, input("First Number: "), input("Second Number: ")) elif(oper == '-'): print ("Subtraction") mathFunc(sub, input("First Number: "), input("Second Number: ")) elif(oper == '*'): print ("Multiplication") mathFunc(mul, input("First Number: "), input("Second Number: ")) elif(oper == '/'): print ("Division") mathFunc(div, input("First Number: "), input("Second Number: ")) elif(oper == 'q'): print ("Quiting...") cnt = False else: print (""" Invalid Input Please choose between +, -, *, / or enter q to Quit Try Again""") sleep(2) clear()
import random # 1) generate random number # 2) take an input (number) from user # 3) compare input to generated number # 4) add higher and lower statements # 5) add 5 guess number = random.randint(1, 50) print(''' Hello welcome to guess game. You have 5 guesses to find the number I have thought. The number is 1 to 50 ''') # print(number) guesses = 5 guess = 0 while guesses > 0 and guess != number: guess = int(input(" ")) if guess == number: print("Correct ") guesses = -1 elif guess < number: print("higher") guesses -= 1 elif guess > number: print("lower") guesses -= 1 if guesses == 0: print("You lost") print("*GAME OVER") if guesses == -1: print("*YOU WIN*")
# Find the greatest common denominator of two numbers # using Euclid's algorithm def gcd(larger_num, smaller_num): original_large = larger_num original_small = smaller_num remainder = 1 while(remainder != 0): remainder = larger_num % smaller_num if remainder == 0: print(f'{smaller_num} is the Greatest Common Divisor between {original_large} and {original_small}') else: larger_num = smaller_num smaller_num = remainder # try out the function with a few examples # print(gcd(98, 60)) # print(gcd(20, 8)) gcd(8, 2) gcd(200, 16) gcd(20, 8)
from string import ascii_lowercase class Puzzle: def __init__(self, test=False): filename = "test.txt" if test else "input.txt" self.data = self.load_into_memory(filename) def load_into_memory(self, filename): """load input into memory (list)""" with open(filename) as f: data = f.read().strip('\n') return data def reduce_polymer(self, polymer): """ Remove units which are adjacent, and of opposing Capitilisation e.g. "a" and "A". Returns remaining units. """ new_polymer = [''] for unit in polymer: prev = new_polymer[-1] if unit != prev and unit.lower() == prev.lower(): new_polymer.pop() else: new_polymer.append(unit) return new_polymer[1:] def solve_part1(self): """ Returns result for part 1: Returns length of returned list of units. """ return len(self.reduce_polymer(self.data)) def solve_part2(self): """ Returns result for part 2: Removes unwanted units after each unit type is removed, in turn. Returns minimum polymer length. """ sizes = [] polymer = self.reduce_polymer(self.data) # speed up for l in ascii_lowercase: test_polymer = [u for u in polymer if u.lower() != l] length = len(self.reduce_polymer(test_polymer)) sizes.append(length) return min(sizes) if __name__ == "__main__": puzzle = Puzzle() print("Part 1 = {}".format(puzzle.solve_part1())) print("Part 2 = {}".format(puzzle.solve_part2()))
from collections import deque, defaultdict from itertools import cycle class Puzzle: def __init__(self, test=False): self.players = 9 if test else 459 self.marbles = 25 if test else 72103 def solve_part1(self): """Returns result for part 1""" d = deque([0]) scores = defaultdict(int) players = cycle(range(self.players)) for m in range(1,self.marbles+1): p = next(players) if m % 23 == 0: d.rotate(7) scores[p] += d.pop() + m d.rotate(-1) else: d.rotate(-1) d.append(m) return max(scores.values()) def solve_part2(self): """Returns result for part 2""" self.marbles *= 100 return self.solve_part1() if __name__ == "__main__": puzzle = Puzzle() print("Part 1 = {}".format(puzzle.solve_part1())) print("Part 2 = {}".format(puzzle.solve_part2()))
#!/usr/bin/env python3 # Random sentence generator # CMPU 240, Fall 2019 import sys import fileinput import random import re grammar = {} def error(msg): """Print an error message and exit.""" print(msg, file=sys.stderr) sys.exit() for line in fileinput.input(): # Skip blank lines if not line.strip(): continue # Split the line into the head and a list of bodies try: head, bodies = line.strip().split(" -> ") bodies = bodies.split(" | ") except ValueError: error("Bad input line: " + line.strip()) if head in grammar: error("All rules for a head need to be on the same line.") grammar[head] = bodies string = "<start>" def generateSentence(fileinput): # select one production of this symbol randomly rand_prod = random.choice(self.prod[fileinput]) for sym in rand_prod: # for non-terminals, recurse if sym in self.prod: string.append(sym) else: string += sym return string # Expand string, printing each step of the expansion, until there are # no non-terminals left.
#kieran burnett #10-10-2014 #ASCII task one num = int(input("Please enter a number to be converted to ASCII: ")) text = input("Please enter a word to be turned into its ASCII number: ") num_p = chr(num) text_p = ord(text) print(" The number you entered in ASCII: ",num_p) print(" Then number of the letter you entered: ",text_p)
""" Catalogue manages library items. It uses LibraryItemGenerator to prompt user with an UI to add different types of library items. """ __author__ = "Jack Shih" __version__ = "Jan 2021" import difflib from library_item_generator import LibraryItemGenerator class Catalogue: def __init__(self, library_item_list): """ Initialize the library with a list of library items. :param library_item_list: a sequence of library_item objects. """ self._library_item_list = library_item_list def find_items(self, title): """ Find items with the same and similar title. :param title: a string :return: a list of titles. """ title_list = [] for library_item in self._library_item_list: title_list.append(library_item.get_title()) results = difflib.get_close_matches(title, title_list, cutoff=0.5) return results def add_item(self): """ Add a brand new item to the library with a unique call number. Redirects user to the LibraryItemGenerator for an UI to add different library items. Calls LibraryItemGenerator's class method. """ # First check if call number already exists. call_number = input("Enter Call Number: ") found_item = self.retrieve_item_by_call_number(call_number) if found_item: print(f"Could not add item with call number " f"{found_item.call_number}. It already exists. ") else: # Add the item with LibraryItemGenerator new_item = LibraryItemGenerator.add_item(call_number) if new_item: self._library_item_list.append(new_item) print("item added successfully! item details:") print(new_item) else: print("item not added") def remove_item(self, call_number): """ Remove an existing item from the library :param call_number: a string :precondition call_number: a unique identifier """ found_item = self.retrieve_item_by_call_number(call_number) if found_item: self._library_item_list.remove(found_item) print(f"Successfully removed {found_item.get_title()} with " f"call number: {call_number}") else: print(f"item with call number: {call_number} not found.") def retrieve_item_by_call_number(self, call_number): """ A private method that encapsulates the retrieval of an item with the given call number from the library. :param call_number: a string :return: item object if found, None otherwise """ found_item = None for library_item in self._library_item_list: if library_item.call_number == call_number: found_item = library_item break return found_item def display_available_items(self): """ Display all the items in the library. """ print("items List") print("--------------", end="\n\n") for library_item in self._library_item_list: print(library_item) print() def reduce_item_count(self, call_number): """ Decrement the item count for an item with the given call number in the library. :param call_number: a string :precondition call_number: a unique identifier :return: True if the item was found and count decremented, false otherwise. """ library_item = self.retrieve_item_by_call_number(call_number) if library_item: library_item.decrement_number_of_copies() return True else: return False def increment_item_count(self, call_number): """ Increment the item count for an item with the given call number in the library. :param call_number: a string :precondition call_number: a unique identifier :return: True if the item was found and count incremented, false otherwise. """ library_item = self.retrieve_item_by_call_number(call_number) if library_item: library_item.increment_number_of_copies() return True else: return False def generate_test_items(self): """ Returns a list of items with dummy data. Calls LibraryItemGenerator's static method. :return: a list """ dummy_item_list = LibraryItemGenerator.generate_test_items() self._library_item_list = dummy_item_list
""" This module contains the Transaction class, which represents one transaction. """ __author__ = "Jack Shih & Tegvaran Sooch" __version__ = "Feb 2021" class Transaction: """ Represents a transaction and the money going in and out of the bank account. """ def __init__(self, timestamp, amount, budget_category, vendor_name): """ Initializes the transaction. :param timestamp: dateTime :param amount: double :param budget_category: budgetCategory :param vendor_name: string """ self._timestamp = timestamp self._amount = amount self._budget_category = budget_category self._vendor_name = vendor_name def get_timestamp(self): """ Gets the timestamp of the transaction :return: dateTime """ return self._timestamp def set_timestamp(self, new_timestamp): """ Sets the new amount of the transactions. :param new_timestamp: datetime """ self._timestamp = new_timestamp def get_amount(self): """ Gets the amount of the transaction. :return: double """ return self._amount def set_amount(self, new_amount): """ Sets the new amount of the transactions. :param new_amount: double """ if new_amount <= 0: print("Please enter an amount that is more than 0.") else: self._amount = new_amount def get_budget_category(self): """ Gets the budget category of the transaction :return: budgetCategory """ return self._budget_category def get_vendor_name(self): """ Gets the name of the vendor where the purchase took place. :return: string """ return self._vendor_name def set_vendor_name(self, new_vendor_name): """ Sets the new vendor name. :param new_vendor_name: string """ self._vendor_name = new_vendor_name def __str__(self): return f"category: {self.budget_category}, amount: {self.amount}, " \ f"vendor: {self.vendor_name}, transaction entered at: {self.timestamp}, " timestamp = property(get_timestamp, set_timestamp) amount = property(get_amount, set_amount) budget_category = property(get_budget_category) vendor_name = property(get_vendor_name, set_vendor_name)
""" This module contains all the Products that the Store sells. For each festive season, the store stocks a unique toy. There are three festive seasons (Christmas, Halloween, Easter) and three types of products (Toy, StuffedAnimal, Candy) for each season, for a total of 9 Products. """ __author__ = "Jack Shih & Tegvaran Sooch" __version__ = "Mar 2021" from enum import Enum, auto class Product: """ Represents a Product. All Products have a unique ID, name, description. and the rest are stored in kwargs. """ YES_OR_NO = "Y, N" def __init__(self, product_id, name, description, **kwargs): self._product_id = product_id self._name = name self._description = description def get_id(self): """ Getter for Product_id :return: string """ return self._product_id def __key(self): """ The unique key for this Product, which an immutable tuple of the unique product_id :return: tuple(string) """ return tuple(self._product_id) def __hash__(self): """ Make Product hashable. This is needed so Product can be used as a key in a dictionary in Inventory. :return: hashed key which is a tuple of product_id """ return hash(self.__key()) def __eq__(self, other): """ Defines how two Products are compared. They are compared by their defined keys, which are their product_ids. :param other: Product, another Product to be compared to this Product :return: boolean """ if isinstance(other, Product): return self.__key() == other.__key() return NotImplemented def __str__(self): """ toString for the Name for the Product. """ return f"{self._name}" id = property(get_id) class Toy(Product): """ Toy as a Product. Information regarding a Toy: • Whether the toy is battery operated or not. • The minimum recommended age of the child that the toy is safe for. """ def __init__(self, product_id, name, description, min_age, has_batteries): """ Initialized the properties that all Toys have. """ super().__init__(product_id, name, description) if has_batteries not in self.YES_OR_NO: raise InvalidDataError("Has batteries", self.YES_OR_NO) else: if has_batteries == "Y": self._battery_operated = True else: self._battery_operated = False if not isinstance(min_age, float): raise InvalidDataError("Minimum Age", "integer") else: self._recommended_age = int(min_age) class SantasWorkshop(Toy): """ Christmas Toy. Not battery operated. Unique properties: • dimensions (width and height), • The number of rooms. """ def __init__(self, num_rooms, dimensions, has_batteries=False, **kwargs): super().__init__(kwargs['product_id'], kwargs["name"], kwargs['description'], kwargs['min_age'], has_batteries) try: dimensions = [int(x) for x in dimensions.split(",")] except ValueError: raise InvalidDataError("Dimensions", "integer") if self._battery_operated: raise InvalidDataError("Has batteries", "N") self._width = dimensions[0] self._height = dimensions[1] if not isinstance(num_rooms, float): raise InvalidDataError("Number of rooms", "Integer") else: self._number_of_rooms = int(num_rooms) class RCSpider(Toy): """ Halloween Toy. Battery operated. Unique properties: • Speed • Jump height • Some spiders glow in the dark, while others do not. • The type of spider - This can either be a Tarantula or a Wolf Spider and nothing else. """ class SpiderType(Enum): """Two types of spiders.""" Tarantula = auto() Wolf_Spider = auto() def __init__(self, speed, jump_height, has_glow, has_batteries=True, **kwargs): super().__init__(kwargs['product_id'], kwargs["name"], kwargs['description'], kwargs['min_age'], has_batteries) try: self._speed = float(speed) except ValueError: raise InvalidDataError("Speed", "integer or float") try: self._jump_height = float(jump_height) except ValueError: raise InvalidDataError("Height", "integer or float") if has_glow not in self.YES_OR_NO: raise InvalidDataError("Has glow", self.YES_OR_NO) else: if has_glow == "Y": self._glow_in_the_dark = True else: self._glow_in_the_dark = False try: self._type = self.SpiderType[kwargs['spider_type'].replace(' ', '_')] except KeyError: raise InvalidDataError("Spider Type", get_key_names_as_string(self.SpiderType)) if not self._battery_operated: raise InvalidDataError("Has batteries", "Y") class RobotBunny(Toy): """ Easter Toy. Battery operated. For toddlers and infants. Unique properties: • The number of sound effects • The colour - This can be either Orange, Blue, or Pink and nothing else """ class Colour(Enum): """ Only three types of colour are available. """ Orange = auto() Blue = auto() Pink = auto() def __init__(self, num_sound, has_batteries=True, **kwargs): super().__init__(kwargs['product_id'], kwargs["name"], kwargs['description'], kwargs['min_age'], has_batteries) try: self._number_of_sound_effects = int(num_sound) except ValueError: raise InvalidDataError("Number of sounds", "integer") try: self._colour = self.Colour[kwargs['colour']] except KeyError: raise InvalidDataError("Colour", get_key_names_as_string(self.Colour)) if not self._battery_operated: raise InvalidDataError("Has batteries", "Y") class StuffedAnimal(Product): """ Toy as a Product. Information regarding a Toy: • Stuffing - This can either be Polyester Fiberfill or Wool • Size - This can either be Small, Medium or Large • Fabric - This can either be Linen, Cotton or Acrylic """ class Stuffing(Enum): """ Only two choices: Polyester Fibrefill or Wool. """ Polyester_Fibrefill = auto() Wool = auto() class Size(Enum): """ Only three choices: Small, Medium or Large. """ S = auto() M = auto() L = auto() class Fabric(Enum): """ Only three choices: Linen, Cotton or Acrylic """ Linen = auto() Cotton = auto() Acrylic = auto() def __init__(self, **kwargs): """ Initializes the properties that all StuffedAnimals have. """ super().__init__(**kwargs) try: self._stuffing = self.Stuffing[kwargs['stuffing'].replace(' ', '_')] except KeyError: raise InvalidDataError("Stuffing", get_key_names_as_string(self.Stuffing)) try: self._size = self.Size[kwargs['size']] except KeyError: raise InvalidDataError("Size", get_key_names_as_string(self.Size)) try: self._fabric = self.Fabric[kwargs['fabric']] except KeyError: raise InvalidDataError("Fabric", get_key_names_as_string(self.Fabric)) class DancingSkeleton(StuffedAnimal): """ Halloween StuffedAnimal. This skeleton is sure to add to your Halloween decorations. • Fabric: Acrylic yarn. • Stuffing: Polyester Fiberfill • Glows in the dark. """ def __init__(self, **kwargs): super().__init__(**kwargs) if self._stuffing != self.Stuffing.Polyester_Fibrefill: raise InvalidDataError("Stuffing", "Polyester Fibrefill") if self._fabric != self.Fabric.Acrylic: raise InvalidDataError("Fabric", "Acrylic Yarn") if kwargs['has_glow'] not in self.YES_OR_NO: raise InvalidDataError("Has Glow", self.YES_OR_NO) else: if kwargs['has_glow'] == "Y": self._glow_in_the_dark = True else: self._glow_in_the_dark = False # self._stuffing = super().Stuffing.Polyester_Fiberfill # self._fabric = super().Fabric.Acrylic class Reindeer(StuffedAnimal): """ Christmas StuffedAnimal. Comes with its very own personal mini sleigh. • Fabric: Cotton. • Stuffing: Wool. • has a glow in the dark nose. """ def __init__(self, **kwargs): super().__init__(**kwargs) if self._stuffing != self.Stuffing.Wool: raise InvalidDataError("Stuffing", "Wool") if self._fabric != self.Fabric.Cotton: raise InvalidDataError("Fabric", "Cotton") if kwargs['has_glow'] not in self.YES_OR_NO: raise InvalidDataError("Has Glow", self.YES_OR_NO) else: if kwargs['has_glow'] == "Y": self._glow_in_the_dark = True else: self._glow_in_the_dark = False # self._stuffing = super().Stuffing.Wool # self._fabric = super().Fabric.Cotton class EasterBunny(StuffedAnimal): """ Easter StuffedAnimal. Comes with its very own personal mini sleigh. • Fabric: Linen. • Stuffing: Polyester Fiberfill. • Four colours: White, Grey, Pink and Blue. """ class Colour(Enum): """ Only four types of colour are available. """ White = auto() Grey = auto() Pink = auto() Blue = auto() def __init__(self, **kwargs): super().__init__(**kwargs) if self._stuffing != self.Stuffing.Polyester_Fibrefill: raise InvalidDataError("Stuffing", "Polyester Fibrefill") if self._fabric != self.Fabric.Linen: raise InvalidDataError("Fabric", "Linen") try: self._colour = self.Colour[kwargs['colour']] except KeyError: raise InvalidDataError("Colour", get_key_names_as_string(self.Colour)) # self._stuffing = super().Stuffing.Polyester_Fiberfill # self._fabric = super().Fabric.Linen class Candy(Product): """ All candies have the following properties: • If it contains any nuts • If it is lactose free. """ def __init__(self, **kwargs): super().__init__(**kwargs) if kwargs['has_nuts'] not in self.YES_OR_NO: raise InvalidDataError("Has Nuts", self.YES_OR_NO) else: if kwargs['has_nuts'] == "Y": self._contains_nuts = True else: self._contains_nuts = False if kwargs['has_lactose'] not in self.YES_OR_NO: raise InvalidDataError("Has Lactose", self.YES_OR_NO) else: if kwargs['has_lactose'] == "Y": self._has_lactose = True else: self._has_lactose = False class PumpkinCaramelToffee(Candy): """ Halloween Candy. • Has Lactose: True • Contains nuts: True • Two varieties: Sea Salt and Regular. """ class Flavour(Enum): """ Can be one of these two varieties. """ Sea_Salt = auto() Regular = auto() def __init__(self, **kwargs): super().__init__(**kwargs) try: self._flavour = self.Flavour[kwargs['variety'].replace(' ', '_')] except KeyError: raise InvalidDataError("Variety", get_key_names_as_string(self.Flavour)) if not self._has_lactose: raise InvalidDataError("Has Lactose", "Y") if not self._contains_nuts: raise InvalidDataError("Has Nuts", "Y") # contains_nuts = True # lactose_free = False class CandyCane(Candy): """ Christmas Candy. • Has Lactose: False • Contains nuts: False • Strips colour: Red or Green """ class Stripes(Enum): """ Stripes on the candy cane can either be Red or Green. """ Red = auto() Green = auto() def __init__(self, **kwargs): super().__init__(**kwargs) try: self._stripes = self.Stripes[kwargs['colour']] except KeyError: raise InvalidDataError("Stripes", get_key_names_as_string(self.Stripes)) # contains_nuts = False # lactose_free = True if self._has_lactose: raise InvalidDataError("Has Lactose", "N") if self._contains_nuts: raise InvalidDataError("Has Nuts", "N") class CremeEgg(Candy): """ Easter Candy. • Has Lactose: True • Contains nuts: True • Pack size: different numbers of creme eggs per pack """ def __init__(self, **kwargs): super().__init__(**kwargs) try: self._pack_size = int(kwargs['pack_size']) except ValueError: raise InvalidDataError("Pack Size", "integer") # contains_nuts = True # lactose_free = False if not self._has_lactose: raise InvalidDataError("Has Lactose", "Y") if not self._contains_nuts: raise InvalidDataError("Has Nuts", "Y") class InvalidDataError(Exception): """ The InvalidDataError is an exception that should be raised when a product is provided with invalid data. """ def __init__(self, detail_type, valid_data): """ Instantiates the exception with the following message: "InvalidDataError - (type) can only be (valid_data) :param detail_type: type of data. :param valid_data: valid data type as a list. """ super().__init__(f"Error! Invalid data type detected.", detail_type, valid_data) def get_key_names_as_string(enum): """ Gets the names of the keys in an enum class as a string. :return: string """ names = "" for i in range(1, len(enum) + 1): name = enum(i).name name = name.replace("_", " ") names += name if i < len(enum): names += " or " return names
# emoji converter dictionary message = input(">") # user input words = message.split(' ') # returns an array split by spaces ' ' emojis = { # define a dictionary of text to emoji ":)": "🙂", ":(": "☹" } output = "" for word in words: # append emoji to output when found, default to original word output += emojis.get(word, word) + " " print(output)
#Olympic Logo import turtle as p def drawCircle(x,y,c = 'red'): p.pu() p.goto(x,y) p.pd() p.color(c) p.circle(30,360) p.pensize(7) drawCircle(0,0,'blue') drawCircle(60,0, 'black') drawCircle(120,0,'red') drawCircle(90,-30,'green') drawCircle(30,-30,'yellow') p.done()
#Multiple Inhertance class A(object): def dothis(self): print('doing this in A') class B(A): pass class C(object): def dothis(self): print('doing this in C') class D(B,C): pass d_inst = D() d_inst.dothis() print(D.mro()) # Output # doing this in A # [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.A'>, <class '__main__.C'>, <class 'object'>] # [my_machine oop_python]$ ## Diamond inhertance class A(object): def dothis(self): print('doing this in A') class B(A): pass class C(A): def dothis(self): print('doing this in C') class D(B,C): pass d_inst = D() d_inst.dothis() print(D.mro()) # Output # doing this in C # [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>] # [my_machine oop_python]$ # Class Methods class InstanceCounter(object): count = 0 def __init__(self, val): self.val = val InstanceCounter.count += 1 def set_val(self, newval): self.val = newval def get_val(self): return self.val @classmethod def get_count(cls): return cls.count a = InstanceCounter(5) b = InstanceCounter(13) c = InstanceCounter(17) for obj in(a,b,c): print("val of obj: %s" % (obj.get_val())) print("count: %s"% (obj.get_count())) print("count(from instance): %s" % (obj.count)) print("Calling from Class iteslf: %s" % (InstanceCounter.get_count())) # Output # val of obj: 5 # count: 3 # count(from instance): 3 # val of obj: 13 # count: 3 # count(from instance): 3 # val of obj: 17 # count: 3 # count(from instance): 3 # Calling from Class iteslf: 3 # [my_machine oop_python]$ # Static Method class InstanceCounter(object): count = 0 def __init__(self,val): self.val = self.filterint(val) InstanceCounter.count += 1 @staticmethod def filterint(value): if not isinstance(value,int): return 0 else: return value a = InstanceCounter(5) b = InstanceCounter(13) c = InstanceCounter(17) d = InstanceCounter('hi') print(a.val , b.val, c.val, d.val) # Output # 5 13 17 0 # [my_machine oop_python]$ # Abstract Class import abc class GetterSetter(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def set_val(self,input): return @abc.abstractmethod def get_val(self): return class MyClass(GetterSetter): def set_val(self,input): self.val = input def get_val(self): return(self.val) x = MyClass() print(x) # Output # <__main__.MyClass object at 0x7f106c99f2e8> # [my_machine oop_python]$
''' import Adafruit_DHT # Set sensor type : Options are DHT11,DHT22 or AM2302 sensor=Adafruit_DHT.DHT11 # Set GPIO sensor is connected to gpio=17 # Use read_retry method. This will retry up to 15 times to # get a sensor reading (waiting 2 seconds between each retry). humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio) # Reading the DHT11 is very sensitive to timings and occasionally # the Pi might fail to get a valid reading. So check if readings are valid. if humidity is not None and temperature is not None: print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)) else: print('Failed to get reading. Try again!') ''' import time import board import adafruit_dht #Initial the dht device, with data pin connected to: dhtDevice = adafruit_dht.DHT11(board.D17) while True: try: # Print the values to the serial port temperature_c = dhtDevice.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity print("Temp: {:.1f} F / {:.1f} C Humidity: {}% " .format(temperature_f, temperature_c, humidity)) except RuntimeError as error: # Errors happen fairly often, DHT's are hard to read, just keep going print(error.args[0]) time.sleep(2.0)
#!/usr/bin/evn python # -*-conding:utf-8 -*- name = input("name:") Age = input("Age:") Job = input("Job:") Salary = input("Salary:") info =''' --------- info of %s------- name:%s Age:%s Job:%s Salary:%s ''' % (name,name,Age,Job,Salary) print(info) info2 = ''' ------ info of {_name} ------ Name:{_name} Age:{_Age} Job:{_Job} Salary:{_Salary} '''.format(__name=name, __Age=Age, __Job=Job, __Salary=Salary) print(info2)
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> #dictionary >>> d1={"sno":525,"sname":"prabhas","year":2001} >>> print(type(d1)) <class 'dict'> >>> d1 {'sno': 525, 'sname': 'prabhas', 'year': 2001} >>> print(d1['sno']) 525 >>> print(d1['sname']) prabhas >>> #change values >>> d1['sno']=527 >>> d1 {'sno': 527, 'sname': 'prabhas', 'year': 2001} >>> #loop in dict >>> for i in d1.keys: print(i) Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> for i in d1.keys: TypeError: 'builtin_function_or_method' object is not iterable >>> for i in d1: print(i) sno sname year >>> for i in d1: print(d1[i]) 527 prabhas 2001 >>> for i in d1.items(): print(i) ('sno', 527) ('sname', 'prabhas') ('year', 2001) >>> #length >>> print(len(d1)) 3 >>> #adding items >>> d1 {'sno': 527, 'sname': 'prabhas', 'year': 2001} >>> d1["mobno"]=9390 >>> d1 {'sno': 527, 'sname': 'prabhas', 'year': 2001, 'mobno': 9390} >>> #pop >>> d1 {'sno': 527, 'sname': 'prabhas', 'year': 2001, 'mobno': 9390} >>> d1.pop("sno") 527 >>> d1 {'sname': 'prabhas', 'year': 2001, 'mobno': 9390} >>> #delete >>> d1 {'sname': 'prabhas', 'year': 2001, 'mobno': 9390} >>> del d1["year"] >>> d1 {'sname': 'prabhas', 'mobno': 9390} >>> del d1 >>> d1 Traceback (most recent call last): File "<pyshell#37>", line 1, in <module> d1 NameError: name 'd1' is not defined >>> #clear >>> d={"name":"ram","college":"cvr","id":19525} >>> d {'name': 'ram', 'college': 'cvr', 'id': 19525} >>> d.clear() >>> d {} >>> #copy dict >>> d={"name":"ram","college":"cvr","id":19525} SyntaxError: unexpected indent >>> d={"name":"ram","college":"cvr","id":19525} >>> d1=d.copy() >>> d1 {'name': 'ram', 'college': 'cvr', 'id': 19525} >>> d2=dict(d1) >>> d2 {'name': 'ram', 'college': 'cvr', 'id': 19525} >>> #nested dicts >>> college={"st1":{"name":"raj","year":2020},"st2":{"name":"kumar","year":2019}} >>> college {'st1': {'name': 'raj', 'year': 2020}, 'st2': {'name': 'kumar', 'year': 2019}} >>> #dict constructor >>> di=dict(brand="rolex",model="fastrack",year=1947) >>> print(type(di)) <class 'dict'> >>> di {'brand': 'rolex', 'model': 'fastrack', 'year': 1947} >>> #checking key existence >>> di {'brand': 'rolex', 'model': 'fastrack', 'year': 1947} >>> if 'model' in di: print("yes") else: SyntaxError: unindent does not match any outer indentation level >>> if 'model' in di: print("yes") yes >>> if 'model' in di: print("yes") else: print("not available") yes >>> di.update({"mobile":762446}) >>> di {'brand': 'rolex', 'model': 'fastrack', 'year': 1947, 'mobile': 762446} >>> >>> >>> #create dict from keyboard >>> =========================================================================== RESTART: F:/python prgms/userdict.py =========================================================================== Traceback (most recent call last): File "F:/python prgms/userdict.py", line 3, in <module> print(type(x)) NameError: name 'x' is not defined >>> =========================================================================== RESTART: F:/python prgms/userdict.py =========================================================================== <class 'dict'> how many elements?3 Enter key:name Enter values:45 dictionary is: {'name': 45} Enter key:phnno Enter values:9949013040 dictionary is: {'name': 45, 'phnno': 9949013040} Enter key:rollno Enter values:525 dictionary is: {'name': 45, 'phnno': 9949013040, 'rollno': 525} >>> college Traceback (most recent call last): File "<pyshell#73>", line 1, in <module> college NameError: name 'college' is not defined >>> college={"st1":{"name":"raj","year":2020},"st2":{"name":"kumar","year":2019}} >>> college {'st1': {'name': 'raj', 'year': 2020}, 'st2': {'name': 'kumar', 'year': 2019}} >>> #nested calls >>> print(college["st2"]["name"]) kumar >>> =========================================================================== RESTART: F:/python prgms/userdict.py =========================================================================== <class 'dict'> how many elements?2 Enter key:name Enter values:prabhaas dictionary is: {'name': 'prabhaas'} Enter key:address Enter values:vasantham dictionary is: {'name': 'prabhaas', 'address': 'vasantham'} >>>
""" Polymorphism is the ability to leverage the same interface for different underlying forms such as data types or classes """ print(12 + 13) print("edureka" + "rocks") print([1, 2] + [3, 4]) # Same Interface but different underlying forms # Prem class Animal: def __init__(self, name): self.name = name def talk(self): pass # Sudiptha class Cat(Animal): def talk(self): print("Meowwwww") # Fred class Dog(Animal): def talk(self): print("Woof") ################# Client/ User ############### c = Cat("Kitty") print(c.talk()) d = Dog("Tommy") print(d.talk())
import tkinter as tk # App Class class App(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self.winfo_toplevel().title("[ Periodic Table of the Elements ]" ) self.topLabel = tk.Label(self, text="Click on an element for more info.", font = 500) self.topLabel.grid(row=0, column=0, columnspan=18) # Names of Buttons in column 1 column1 = [ ('H', 'Hydrogen', 'Atomic No= 1\nAtomic Mass= 1.008 u\nAtomic Radius= 120 pm \nState = Gas\nCategory = Non Metal\nDensity= 0.00008988 g/cm³\nBoiling Point = 20.28 K\nMelting point = 13.81 K\nElectronic Configuration = 1s2\nYear Discovered= 1868'), ('Li', 'Lithium', 'Atomic No= 3\nAtomic Mass= 7.0 u\nAtomic Radius= 182 pm\nState Solid= \nCategory = Alkali Metal\nDensity= 0.534 g/cm³\nBoiling Point = 1615 K\nMelting point = 453.65 K \nElectronic Configuration = [He]2s1 \nYear Discovered= 1766'), ('Na', 'Sodium', 'Atomic No= 11\nAtomic Mass= 22.99u u\nAtomic Radius= 227 pm\nState = Solid\nCategory = Alkali Metal\nDensity= 0.97 g/cm³\nBoiling Point = 1156 K\nMelting point = 370.95 K\nElectronic Configuration = [Ne]3s1\nYear Discovered= 1807'), ('K', 'Potassium', 'Atomic No= 19\nAtomic Mass= 39.1 u\nAtomic Radius= 275 pm\nState = Solid\nCategory = Alkali Metal\nDensity= 0.89 g/cm³\nBoiling Point = 1032 K\nMelting point = 336.53 K\nElectronic Configuration = [Ar]4s1\nYear Discovered= 1807'), ('Rb', 'Rubudium', 'Atomic No= 37\nAtomic Mass= 85.47 u\nAtomic Radius= 303 pm\nState = Solid\nCategory = Alkali Metal\nDensity= 1.53 g/cm³\nBoiling Point = 961 K\nMelting point = 312.46 K\nElectronic Configuration = [Kr]5s1\nYear Discovered= 1861'), ('Cs', 'Cesium', 'Atomic No= 55\nAtomic Mass= 132.90 u\nAtomic Radius= 343 pm\nState = Solid\nCategory = Alkali Metal\nDensity= 1.93 g/cm³\nBoiling Point = 944 K\nMelting point = 301.59 K\nElectronic Configuration = [Xe]6s1\nYear Discovered= 1860'), ('Fr', 'Francium', 'Atomic No= 87\nAtomic Mass= 223.109 u\nAtomic Radius= 348 pm\nState = Solid\nCategory = Alkali Metal\nDensity= NA\nBoiling Point = NA\nMelting point = 300K\nElectronic Configuration = [Rn]7s1\nYear Discovered= 1939') ] r = 1 c = 0 count = 0 for b in column1: tk.Button(self, text=b[0], width=5, height=4, bg="firebrick1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column2 = [ ('Be', 'Beryllium', 'Atomic No= 4\nAtomic Mass= 9.0123 u\nAtomic Radius= 153 pm\nState = Solid\nCategory = Alkaline Earth Metal\nDensity= 1.85 g/cm³\nBoiling Point = 2744 K\nMelting point = 1560 K\nElectronic Configuration = [He]2s2\nYear Discovered= 1797'), ('Mg', 'Magnesium', 'Atomic No= 12\nAtomic Mass= 24.305 u\nAtomic Radius= 173pm\nState = Solid\nCategory = Alkaline Earth Metal\nDensity= 1.74 g/cm³\nBoiling Point = 1363 K\nMelting point = 923 K\nElectronic Configuration = [Ne]3s2\nYear Discovered= 1755'), ('Ca', 'Calcium', 'Atomic No= 20\nAtomic Mass= 40.08 u\nAtomic Radius= 231 pm\nState = Solid\nCategory = Alkaline Earth Metal\nDensity= 1.55 g/cm³\nBoiling Point = 1757 K\nMelting point = 1115 K\nElectronic Configuration = [Ar]4s2\nYear Discovered= 1808'), ('Sr', 'Strontium', 'Atomic No= 38\nAtomic Mass= 87.6 u\nAtomic Radius= 249 pm\nState = Solid\nCategory = Alkaline Earth Metal\nDensity= 2.64 g/cm³\nBoiling Point = 1655 K\nMelting point = 1050 K\nElectronic Configuration = [Kr]5s2\nYear Discovered= 1790'), ('Ba', 'Barium', 'Atomic No= 56\nAtomic Mass= 137.33 u\nAtomic Radius= 268 pm\nState = Solid\nCategory = Alkaline Earth Metal\nDensity= 3.62 g/cm³\nBoiling Point = 2170 K\nMelting point = 1000 K \nElectronic Configuration = [Xe]6s2 \nYear Discovered= 1808'), ('Ra', 'Radium', 'Atomic No= 88\nAtomic Mass= 226.025 u\nAtomic Radius= 283 pm\nState = Solid\nCategory = Alkaline Earth Metal\nDensity= 5.5 g/cm³\nBoiling Point = 1413 K\nMelting point = 973 K\nElectronic Configuration = [Rn]7s2\nYear Discovered= 1898') ] r = 2 c = 1 for b in column2: tk.Button(self, text=b[0], width=5, height=4, bg="darkorange1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column3 = [ ('Sc', 'Scandium', 'Atomic No= 21\nAtomic Mass= 44.955 u\nAtomic Radius= 211 pm\nState = Solid\nCategory = Transition Metal\nDensity= 2.99 g/cm³\nBoiling Point = 3109 K \nMelting point = 1814 K\nElectronic Configuration = [Ar]4s23d1\nYear Discovered= 1879'), ('Y', 'Yttrium', 'Atomic No= 39\nAtomic Mass= 88.905 u\nAtomic Radius= 219 pm\nState = Solid\nCategory = Transition Metal\nDensity= 4.47 g/cm³\nBoiling Point = 3618 K\nMelting point = 1795 K\nElectronic Configuration = [Kr]5s24d1\nYear Discovered= 1794'), ('La >|', 'Lanthanum', 'Atomic No= 57\nAtomic Mass= 138.905 u\nAtomic Radius= 240 pm\nState = Solid\nCategory = Lanthanide\nDensity= 6.15 g/cm³\nBoiling Point = 3737 K\nMelting point = 1191 K\nElectronic Configuration = [Xe]6s25d1\nYear Discovered= 1839'), ('Ac >|', 'Actinium', 'Atomic No= 89\nAtomic Mass= 227.027 u\nAtomic Radius= 260 pm\nState = Solid\nCategory = Actinide\nDensity= 10.07 g/cm³\nBoiling Point = 3471 K\nMelting point = 1324 K\nElectronic Configuration = [Rn]7s26d1\nYear Discovered= 1899') ] r = 4 c = 2 for b in column3: tk.Button(self, text=b[0], width=5, height=4, bg="goldenrod1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column4 = [ ('Ti', 'Titanium', 'Atomic No= 22\nAtomic Mass= 47.87 u\nAtomic Radius= 187 pm\nState = Solid\nCategory = Transition Metal\nDensity= 4.5 g/cm³\nBoiling Point = 3560 K\nMelting point = 1941 K\nElectronic Configuration = [Ar]4s23d2 \nYear Discovered= 1791'), ('Zr', 'Zirconium', 'Atomic No= 40\nAtomic Mass= 91.22 u\nAtomic Radius= 186 pm\nState = Solid\nCategory = Transition Metal\nDensity= 6.52 g/cm³\nBoiling Point = 4682 K\nMelting point = 2128 K\nElectronic Configuration = [Kr]5s24d2\nYear Discovered= 1789'), ('Hf', 'Hafnium', 'Atomic No= 72\nAtomic Mass= 178.49 u\nAtomic Radius= 212 pm\nState = Solid\nCategory = Transition Metal\nDensity= 13.3 g/cm³\nBoiling Point = 4876 K\nMelting point = 2506 K\nElectronic Configuration = [Xe]6s24f145d2\nYear Discovered= 1923'), ('Rf', 'Rutherfordium', 'Atomic No= 104\nAtomic Mass= 267.122 u\nAtomic Radius= 267 pm\nState = Solid\nCategory = Transition Metal\nDensity= 23.2 g/cm³\nBoiling Point = 5773.15 K\nMelting point = 2373.15 K\nElectronic Configuration = [Rn]7s25f146d2\nYear Discovered= 1964') ] r = 4 c = 3 for b in column4: tk.Button(self, text=b[0], width=5, height=4, bg="goldenrod1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 10: r = 1 c += 1 column5 = [ ('V', 'Vanadium', 'Atomic No= 23\nAtomic Mass= 50.94 u\nAtomic Radius= 179 pm\nState = Solid\nCategory = Transition Metal\nDensity= 6.0 g/cm³\nBoiling Point = 3680 K\nMelting point = 2183 K\nElectronic Configuration = [Ar]4s23d3 \nYear Discovered= 1801'), ('Nb', 'Niobium', 'Atomic No= 41\nAtomic Mass= 92.906 u\nAtomic Radius= 207 pm\nState = Solid\nCategory = Transition Metal\nDensity= 8.57 g/cm³\nBoiling Point = 5017 K\nMelting point = 2750 K\nElectronic Configuration = [Kr]5s14d4\nYear Discovered= 1801'), ('Ta', 'Tantalum', 'Atomic No= 73\nAtomic Mass= 180.947 u\nAtomic Radius= 217 pm\nState = Solid\nCategory = Transition Metal\nDensity= 16.4 g/cm³\nBoiling Point = 5731 K\nMelting point = 3290 K\nElectronic Configuration = [Xe]6s24f145d3\nYear Discovered= 1802'), ('Db', 'Dubnium', 'Atomic No= 105\nAtomic Mass= 262 u\nAtomic Radius= 268 pm\nState = Solid\nCategory = Transition Metal\nDensity= 29.3 g/cm3\nBoiling Point = NA\nMelting point = Na\nElectronic Configuration = [Rn]7s25f146d3\nYear Discovered= 1967') ] r = 4 c = 4 for b in column5: tk.Button(self, text=b[0], width=5, height=4, bg="goldenrod1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 10: r = 1 c += 1 column6 = [ ('Cr', 'Chromium', 'Atomic No= 24\nAtomic Mass= 51.996 u\nAtomic Radius= 189 pm\nState = Solid\nCategory = Transition Metal\nDensity= 7.15 g/cm³\nBoiling Point = 2944 K\nMelting point = 2180 K\nElectronic Configuration = [Ar]3d54s1 \nYear Discovered= 1797'), ('Mo', 'Molybdenum', 'Atomic No= 42\nAtomic Mass= 96 u\nAtomic Radius= 209 pm\nState = Solid\nCategory = Transition Metal\nDensity= 10.2 g/cm³\nBoiling Point = 4912 K\nMelting point = 2896 K\nElectronic Configuration = [Kr]5s14d5\nYear Discovered= 1778'), ('W', 'Tungsten', 'Atomic No= 74\nAtomic Mass= 183.8 u\nAtomic Radius= 210 pm\nState = Solid\nCategory = Transition Metal\nDensity= 19.3 g/cm³\nBoiling Point = 5828 K\nMelting point = 3695 K\nElectronic Configuration = [Xe]6s24f145d4\nYear Discovered= 1783'), ('Sg', 'Seaborgium', 'Atomic No= 106\nAtomic Mass= 269.128 u\nAtomic Radius= 143pm\nState = Solid\nCategory = Transition Metal\nDensity= 35g/cm³\nBoiling Point = NA\nMelting point = NA\nElectronic Configuration = [Rn]7s25f146d4\nYear Discovered= 1974') ] r = 4 c = 5 for b in column6: tk.Button(self, text=b[0], width=5, height=4, bg="goldenrod1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column7 = [ ('Mn', 'Manganese', 'Atomic No= 25\nAtomic Mass= 54.93 u\nAtomic Radius= 197 pm\nState = Solid\nCategory = Transition Metal\nDensity= 7.3 g/cm³\nBoiling Point = 2334 K\nMelting point = 1519 K\nElectronic Configuration = [Ar]4s23d5 \nYear Discovered= 1774'), ('Tc', 'Technetium', 'Atomic No= 43\nAtomic Mass= 96.90 u\nAtomic Radius= 209 pm\nState = Solid\nCategory = Transtion Metal\nDensity= 11 g/cm³\nBoiling Point = 4538 K\nMelting point = 2430 K\nElectronic Configuration = [Kr]5s24d5\nYear Discovered= 1937'), ('Re', 'Rhenium', 'Atomic No= 75\nAtomic Mass= 186.21 u\nAtomic Radius= 217 pm\nState = Solid\nCategory = Transition Metal\nDensity= 20.8 g/cm³\nBoiling Point = 5869 K\nMelting point = 3459 K\nElectronic Configuration = [Xe]6s24f145d5\nYear Discovered= 1925'), ('Bh', 'Bohrium', 'Atomic No= 107\nAtomic Mass= 270.13 u\nAtomic Radius= 141 pm\nState = Solid\nCategory = Transiton Metal\nDensity= 37 g/cm³\nBoiling Point = NA\nMelting point = NA\nElectronic Configuration = [Rn]7s25f146d5\nYear Discovered= 1976') ] r = 4 c = 6 for b in column7: tk.Button(self, text=b[0], width=5, height=4, bg="goldenrod1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column8 = [ ('Fe', 'Iron', 'Atomic No= 26\nAtomic Mass= 55.84 u\nAtomic Radius= 194 pm\nState = Solid\nCategory = Transition Metal\nDensity= 7.874 g/cm³\nBoiling Point = 3134 K\nMelting point = 1811 K\nElectronic Configuration = [Ar]4s23d6\nYear Discovered= Ancient'), ('Ru', 'Ruthenium', 'Atomic No= 44\nAtomic Mass= 101.1 u\nAtomic Radius= 207 pm\nState = Solid\nCategory = Transition Metal\nDensity= 12.1 g/cm³\nBoiling Point = 4423 K\nMelting point = 2607 K\nElectronic Configuration = [Kr]5s14d7\nYear Discovered= 1827'), ('Os', 'Osmium', 'Atomic No= 76\nAtomic Mass= 190.2 u\nAtomic Radius= 216 pm\nState = Solid\nCategory = Transition Metal\nDensity= 22.57 g/cm³\nBoiling Point = 5285 K\nMelting point = 3306 K\nElectronic Configuration = [Xe]6s24f145d6\nYear Discovered= 1803'), ('Hs', 'Hassium', 'Atomic No= 108\nAtomic Mass= 269.13 u\nAtomic Radius= 134 pm\nState = Solid\nCategory = Transition Metal\nDensity= 41 g/cm³\nBoiling Point = NA\nMelting point = NA\nElectronic Configuration = [Rn]7s25f146d6\nYear Discovered= 1984') ] r = 4 c = 7 for b in column8: tk.Button(self, text=b[0], width=5, height=4, bg="goldenrod1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column9 = [ ('Co', 'Cobalt', 'Atomic No= 27\nAtomic Mass= 58.93 u\nAtomic Radius= 192 pm\nState = Solid\nCategory = Transition Metal\nDensity= 8.86 g/cm³\nBoiling Point = 3200 K\nMelting point = 1768 K\nElectronic Configuration = [Ar]4s23d7\nYear Discovered= 1735'), ('Rh', 'Rhodium', 'Atomic No= 45\nAtomic Mass= 102.90 u\nAtomic Radius= 195 pm\nState = Solid\nCategory = Transition Metal\nDensity= 12.4 g/cm³\nBoiling Point = 3968 K\nMelting point = 2237 K\nElectronic Configuration = [Kr]5s14d8\nYear Discovered= 1803'), ('Ir', 'Iridium', 'Atomic No= 77\nAtomic Mass= 192.22 u\nAtomic Radius= 202 pm\nState = Solid\nCategory = Transition Metal\nDensity= 22.42 g/cm³\nBoiling Point = 4701 K\nMelting point = 2719 K\nElectronic Configuration = [Xe]6s24f145d7\nYear Discovered= 1803'), ('Mt', 'Meitnerium', 'Atomic No= 109\nAtomic Mass= 227.15 u\nAtomic Radius= 129\nState = Solid\nCategory = Transition Metal\nDensity= 37.4 g/cm³\nBoiling Point = NA\nMelting point = NA\nElectronic Configuration = [Rn]7s25f146d7\nYear Discovered= 1982') ] r = 4 c = 8 for b in column9: tk.Button(self, text=b[0], width=5, height=4, bg="goldenrod1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column10 = [ ('Ni', 'Nickel', 'Atomic No= 28\nAtomic Mass= 58.69 u\nAtomic Radius= 163 pm\nState = Solid\nCategory = Transition Metal\nDensity= 8.912 g/cm³\nBoiling Point = 3186 K\nMelting point = 1728 K\nElectronic Configuration = [Ar]4s23d8 \nYear Discovered= 1751'), ('Pd', 'Palladium', 'Atomic No= 46\nAtomic Mass= 106.4 u\nAtomic Radius= 202 pm\nState = Solid\nCategory = Transition Metal\nDensity= 12.0 g/cm³\nBoiling Point = 3236 K\nMelting point = 1828.05 K\nElectronic Configuration = [Kr]4d10\nYear Discovered= 1803'), ('Pt', 'Platinum', 'Atomic No= 78\nAtomic Mass= 195.08 u\nAtomic Radius= 209 pm\nState = Solid\nCategory = Transition Metal\nDensity= 21.46 g/cm³\nBoiling Point = 4098 K\nMelting point = 2041.55 K\nElectronic Configuration = [Xe]6s14f145d9\nYear Discovered= 1735') ] r = 4 c = 9 for b in column10: tk.Button(self, text=b[0], width=5, height=4, bg="goldenrod1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column11 = [ ('Cu', 'Copper', 'Atomic No= 29\nAtomic Mass= 63.55 u\nAtomic Radius= 140 pm\nState = Solid\nCategory = Transition Metal\nDensity= 8.933 g/cm³\nBoiling Point = 2835 K\nMelting point = 1357.77 K\nElectronic Configuration = [Ar]4s13d10\nYear Discovered= Ancient'), ('Ag', 'Silver', 'Atomic No= 47\nAtomic Mass= 107.86 u\nAtomic Radius= 172 pm\nState = Solid\nCategory = Transition Metal\nDensity= 10.501 g/cm³\nBoiling Point = 2435 K\nMelting point = 1234.93 K\nElectronic Configuration = [Kr]5s14d10\nYear Discovered= Ancient'), ('Au', 'Gold', 'Atomic No= 79\nAtomic Mass= 196.96 u\nAtomic Radius= 166 pm\nState = Solid\nCategory = Transition Metal\nDensity= 19.28 g/cm³\nBoiling Point = 3129 K\nMelting point = 1337.33K\nElectronic Configuration = [Xe]6s14f145d10\nYear Discovered= Ancient') ] r = 4 c = 10 for b in column11: tk.Button(self, text=b[0], width=5, height=4, bg="goldenrod1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column12 = [ ('Zn', 'Zinc', 'Atomic No= 30\nAtomic Mass= 65.4 u\nAtomic Radius= 139 pm\nState = Solid\nCategory = Transition Metal\nDensity= 7.134 g/cm³\nBoiling Point = 1180 K\nMelting point = 692.69 K\nElectronic Configuration =[Ar]4s23d10 \nYear Discovered= 1746'), ('Cd', 'Cadmium', 'Atomic No= 48\nAtomic Mass= 112.41 u\nAtomic Radius= 158 pm\nState = Solid\nCategory = Transition Metal\nDensity= 8.69 g/cm³\nBoiling Point = 1040 K\nMelting point = 594.22 K\nElectronic Configuration = [Kr]5s24d10 \nYear Discovered= 1817'), ('Hg', 'Mercury', 'Atomic No= 80\nAtomic Mass= 200.59 u\nAtomic Radius= 209 pm\nState = Liquid\nCategory = Transition Metal\nDensity= 13.5336 g/cm³\nBoiling Point = 629.88 K\nMelting point = 234.32 K\nElectronic Configuration = [Xe]6s24f145d10 \nYear Discovered= Ancient') ] r = 4 c = 11 for b in column12: tk.Button(self, text=b[0], width=5, height=4, bg="goldenrod1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column13_1 = [ ('B', 'Boron', 'Atomic No= 5\nAtomic Mass= 10.81 u\nAtomic Radius= 192 pm\nState = Solid\nCategory = Metalloid\nDensity= 2.37 g/cm³\nBoiling Point = 4273 K\nMelting point = 2348 K\nElectronic Configuration =[He]2s22p1 \nYear Discovered= 1808') ] r = 2 c = 12 for b in column13_1: tk.Button(self, text=b[0], width=5, height=4, bg="deeppink", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column13_2 = [ ('Al', 'Aluminium', 'Atomic No= 13\nAtomic Mass= 26.98 u\nAtomic Radius= 184 pm\nState = Solid\nCategory = Post-Transition Metal\nDensity= 2.70 g/cm³\nBoiling Point = 2792 K\nMelting point = 933.43 K\nElectronic Configuration = [Ne]3s23p1 \nYear Discovered= Ancient'), ('Ga', 'Gallium', 'Atomic No= 31\nAtomic Mass= 69.72 u\nAtomic Radius= 187 pm\nState = Solid\nCategory = Post-Transition Metal\nDensity= 5.91 g/cm³\nBoiling Point = 2477 K\nMelting point = 302.91 K\nElectronic Configuration = [Ar]4s23d104p1\nYear Discovered= 1875'), ('In', 'Indium', 'Atomic No= 49\nAtomic Mass= 114.82 u\nAtomic Radius= 193 pm\nState = Solid\nCategory = Post-Transition Metal\nDensity= 7.31 g/cm³\nBoiling Point = 2345 K\nMelting point = 429.75 K\nElectronic Configuration = [Kr]5s24d105p1\nYear Discovered= 1863'), ('Tl', 'Thallium', 'Atomic No= 81\nAtomic Mass= 204.38 u u\nAtomic Radius= 196 pm\nState = Solid\nCategory = Post Transition Metal\nDensity= 11.8 g/cm³\nBoiling Point = 1746 K\nMelting point = 577K\nElectronic Configuration = [Xe]6s24f145d106p1\nYear Discovered= 1861') ] r = 3 c = 12 for b in column13_2: tk.Button(self, text=b[0], width=5, height=4, bg="mediumpurple1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column14_1 = [ ('C', 'Carbon', 'Atomic No= 6\nAtomic Mass= 12.011 u\nAtomic Radius= 170 pm\nState = Solid\nCategory = Non Metal\nDensity= 2.2670 g/cm³\nBoiling Point = 4098 K \nMelting point = 3823 K\nElectronic Configuration = [He]2s22p2\nYear Discovered= Ancient'), ('Si', 'Silicon', 'Atomic No= 14\nAtomic Mass= 28.085 u\nAtomic Radius= 210 pm\nState = Solid\nCategory = Metalloid\nDensity= 2.3296 g/cm³\nBoiling Point = 3538 K\nMelting point = 1687 K\nElectronic Configuration = [Ne]3s23p2\nYear Discovered= 1854') ] r = 2 c = 13 for b in column14_1: tk.Button(self, text=b[0], width=5, height=4, bg="deeppink", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column14_2 = [ ('Ge', 'Germanium', 'Atomic No= 32\nAtomic Mass= 72.63 u\nAtomic Radius= 211 pm\nState = Solid\nCategory = Metalloid\nDensity= 5.323 g/cm³\nBoiling Point = 3106 K\nMelting point = 1211.4 K\nElectronic Configuration = [Ar]4s23d104p2 \nYear Discovered= 1886'), ('Sn', 'Tin', 'Atomic No= 50\nAtomic Mass= 118.71 u\nAtomic Radius= 217 pm\nState = Solid\nCategory = Post-Transition Metal\nDensity= 7.287 g/cm³\nBoiling Point = 2875 K\nMelting point = 505.08 K\nElectronic Configuration = [Kr]5s24d105p2\nYear Discovered= Ancient'), ('Pb', 'Lead', 'Atomic No= 82\nAtomic Mass= 207.2 u\nAtomic Radius= 202 pm \nState = Solid\nCategory = Post-Transition Metal\nDensity= 11.342 g/cm³\nBoiling Point = 2022 K\nMelting point = 600.61 K\nElectronic Configuration = [Xe]6s24f145d106p2\nYear Discovered= Ancient') ] r = 4 c = 13 for b in column14_2: tk.Button(self, text=b[0], width=5, height=4, bg="mediumpurple1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column15_1 = [ ('N', 'Nitrogen', 'Atomic No= 7\nAtomic Mass= 14.007 u\nAtomic Radius= 155 pm\nState = Gas\nCategory = Non Metal\nDensity= 0.0012506 g/cm³\nBoiling Point = 77.3 K\nMelting point = 63.15 K\nElectronic Configuration = [He]2s22p3\nYear Discovered= 1772'), ('P', 'Phosphorus', 'Atomic No= 15\nAtomic Mass= 30.97 u\nAtomic Radius= 180pm\nState = Solid\nCategory = Non Metal\nDensity= 1.82 g/cm³\nBoiling Point = 553.65 K\nMelting point = 317.3 K\nElectronic Configuration = [Ne]3s23p3\nYear Discovered= 1669'), ('As', 'Arsenic', 'Atomic No= 33\nAtomic Mass= 74.92 u\nAtomic Radius= 185 pm\nState = Solid\nCategory = Metalloid\nDensity= 5.776 g/cm³\nBoiling Point = 887 K\nMelting point = 1090 K\nElectronic Configuration = [Ar]4s23d104p3\nYear Discovered= Ancient') ] r = 2 c = 14 for b in column15_1: tk.Button(self, text=b[0], width=5, height=4, bg="deeppink", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column15_2 = [ ('Sb', 'Antimony', 'Atomic No= 51\nAtomic Mass= 121.76 u\nAtomic Radius= 206 pm\nState = Solid\nCategory = Metalloid\nDensity= 6.685 g/cm³\nBoiling Point = 1860 K\nMelting point = 903.7 K\nElectronic Configuration = [Kr]5s24d105p3\nYear Discovered= Ancient'), ('Bi', 'Bismuth', 'Atomic No= 83\nAtomic Mass= 208.98 u\nAtomic Radius= 207 pm\nState = Solid\nCategory = Post-Transition Metal\nDensity= 9.807 g/cm³\nBoiling Point = 1837 K\nMelting point = 544.5 K\nElectronic Configuration = [Xe]6s24f145d106p3\nYear Discovered= 1753') ] r = 5 c = 14 for b in column15_2: tk.Button(self, text=b[0], width=5, height=4, bg="mediumpurple1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column16_1 = [ ('O', 'Oxygen', 'Atomic No= 8\nAtomic Mass= 15.999 u\nAtomic Radius= 152 pm\nState = Gas\nCategory = Non Metal\nDensity= 0.001429 g/cm³\nBoiling Point = 90.2 K\nMelting point = 54.36 K\nElectronic Configuration = [He]2s22p4\nYear Discovered= 1774'), ('S', 'Sulphur', 'Atomic No= 16\nAtomic Mass= 32.07 u\nAtomic Radius= 180 pm\nState = Solid\nCategory = Non Metal\nDensity= 2.067 g/cm³\nBoiling Point = 717.75 K\nMelting point = 388.36 K\nElectronic Configuration = [Ne]3s23p4\nYear Discovered= Ancient'), ('Se', 'Selenium', 'Atomic No= 34\nAtomic Mass= 78.97 u\nAtomic Radius= 190 pm\nState = Solid\nCategory = Non Metal\nDensity= 4.809 g/cm³\nBoiling Point = 958 K\nMelting point = 493.65 K\nElectronic Configuration = [Ar]4s23d104p4\nYear Discovered= 1817'), ('Te', 'Tellurium', 'Atomic No= 52\nAtomic Mass= 127.6 u\nAtomic Radius= 206 pm\nState = Solid\nCategory = Metalloid\nDensity= 6.232 g/cm³\nBoiling Point = 1261 K\nMelting point = 722.66 K\nElectronic Configuration = [Kr]5s24d105p4 \nYear Discovered= 1782') ] r = 2 c = 15 for b in column16_1: tk.Button(self, text=b[0], width=5, height=4, bg="deeppink", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column16_2 = [ ('Po', 'Polonium', 'Atomic No= 84\nAtomic Mass= 208.98 u\nAtomic Radius= 197 pm\nState = Solid\nCategory = Metalloid\nDensity= 9.32 g/cm³\nBoiling Point = 1235 K\nMelting point = 527 K\nElectronic Configuration = [Xe]6s24f145d106p4\nYear Discovered= 1898') ] r = 6 c = 15 for b in column16_2: tk.Button(self, text=b[0], width=5, height=4, bg="mediumpurple1", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column17 = [ ('F', 'Fluorine', 'Atomic No= 9\nAtomic Mass= 18.998 u\nAtomic Radius= 135 pm\nState = Gas\nCategory = Halogen\nDensity= 0.001696 g/cm³\nBoiling Point = 85.03 K\nMelting point = 53.5 K\nElectronic Configuration = [He]2s22p5\nYear Discovered= 1670'), ('Cl', 'Chlorine', 'Atomic No= 17\nAtomic Mass= 35.45 u\nAtomic Radius= 175 pm\nState = Gas\nCategory = Halogen\nDensity= 0.003214 g/cm³\nBoiling Point = 239.11 K\nMelting point = 171.65 K\nElectronic Configuration = [Ne]3s23p5\nYear Discovered= 1774'), ('Br', 'Bromine', 'Atomic No= 35\nAtomic Mass= 79.90 u\nAtomic Radius= 183 pm\nState = Liquid\nCategory = Halogen\nDensity= 3.11 g/cm³\nBoiling Point = 331.95 K\nMelting point = 265.95 K\nElectronic Configuration = [Ar]4s23d104p5\nYear Discovered= 1826'), ('I', 'Iodine', 'Atomic No= 53\nAtomic Mass= 126.904 u\nAtomic Radius= 198 pm\nState = Solid\nCategory = Halogen\nDensity= 4.93 g/cm³\nBoiling Point = 457.55 K\nMelting point = 386..85 K\nElectronic Configuration = [Kr]5s24d105p5\nYear Discovered= 1811'), ('At', 'Astatine', 'Atomic No= 85\nAtomic Mass= 209.98 u\nAtomic Radius= 202 pm\nState = Solid\nCategory = Halogen\nDensity= 7 g/cm³\nBoiling Point = NA\nMelting point = 575 K\nElectronic Configuration = [Xe]6s24f145d106p5\nYear Discovered= 1940') ] r = 2 c = 16 for b in column17: tk.Button(self, text=b[0], width=5, height=4, bg="deeppink", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 column18 = [ ('He', 'Helium', 'Atomic No= 2\nAtomic Mass= 4.0026 u\nAtomic Radius= 140 pm\nState = Gas\nCategory = Noble Gas\nDensity= 0.0001785 g/cm³\nBoiling Point = 4.22 K\nMelting point = 0.95 K\nElectronic Configuration = 1s2\nYear Discovered= 1868'), ('Ne', 'Neon', 'Atomic No= 10\nAtomic Mass= 20.18 u\nAtomic Radius= 154 pm\nState = Gas\nCategory = Noble Gas\nDensity= 0.0008999 g/cm³\nBoiling Point = 27.07 K\nMelting point = 24.56 K\nElectronic Configuration = [He]2s22p6\nYear Discovered= 1898'), ('Ar', 'Argon', 'Atomic No= 18\nAtomic Mass= 39.9 u\nAtomic Radius= 188 pm\nState = Gas\nCategory = Noble Gas\nDensity= 0.0017837 g/cm³\nBoiling Point = 87.3 K\nMelting point = 15.75 K\nElectronic Configuration = [Ne]3s23p6\nYear Discovered= 1894'), ('Kr', 'Krypton', 'Atomic No= 36\nAtomic Mass= 83.80 u\nAtomic Radius= 202 pm\nState = Gas\nCategory = Noble Gas\nDensity= 0.003733 g/cm³\nBoiling Point = 119.93 K\nMelting point = 115.79 K\nElectronic Configuration = [Ar]4s23d104p6\nYear Discovered= 1896'), ('Xe', 'Xenon', 'Atomic No= 54\nAtomic Mass= 131.29 u\nAtomic Radius= 216 pm\nState = Gas\nCategory = Noble Gas\nDensity= 0.005887 g/cm³\nBoiling Point = 165.03 K\nMelting point = 161.63 K\nElectronic Configuration = [Kr]5s24d105p6\nYear Discovered= 1898'), ('Rn', 'Radon', 'Atomic No= 86\nAtomic Mass= 222.0175 u\nAtomic Radius= 220 pm\nState = Gas\nCategory = Noble Gas\nDensity= 0.00973 g/cm³\nBoiling Point = 211.45 K\nMelting point = 202 K\nElectronic Configuration = [Xe]6s24f145d106p6\nYear Discovered= 1900') ] r = 1 c = 17 for b in column18: tk.Button(self, text=b[0], width=5, height=4, bg="deepskyblue", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 self.fillerLine = tk.Label(self, text="") self.fillerLine.grid(row=10, column=0) lanthanide = [ ('>| Ce', 'Cerium', 'Atomic No= 58\nAtomic Mass= 140.12 u\nAtomic Radius= 235 pm\nState = Solid\nCategory = Lanthanide\nDensity= 6.770 g/cm³\nBoiling Point = 3697 K\n Melting point = 1071 K\n Electronic Configuration = [Xe]6s24f15d1\nYear Discovered= 1803'), ('Pr', 'Praseodymium', 'Atomic No= 59\nAtomic Mass= 140.90 u\nAtomic Radius= 239 pm\nState = Solid\nCategory = Lanthanide\nDensity= 6.77 g/cm³\nBoiling Point = 3793 K\nMelting point = 1204 K\nElectronic Configuration = [Xe]6s24f3\nYear Discovered= 1885'), ('Nd', 'Neodymium', 'Atomic No= 60\nAtomic Mass= 144.24 u\nAtomic Radius= 229 pm\nState = Solid\nCategory = Lanthanide\nDensity= 7.01 g/cm³\nBoiling Point = 3347 K\nMelting point = 1294 K \nElectronic Configuration = [Xe]6s24f4\nYear Discovered= 1885'), ('Pm', 'Prothemium', 'Atomic No= 61\nAtomic Mass= 144.91 u\nAtomic Radius= 236 pm\nState = Solid\nCategory = Lanthanide\nDensity= 7.26 g/cm³\nBoiling Point = 3271 K\nMelting point = 1315 K\nElectronic Configuration = [Xe]6s24f5\nYear Discovered= 1945'), ('Sm', 'Samarium', 'Atomic No= 62\nAtomic Mass= 150.4 u\nAtomic Radius= 229 pm\nState = Solid \nCategory = Lanthanide\nDensity= 7.52 g/cm³\nBoiling Point = 2067 K\nMelting point = 1347 K\nElectronic Configuration = [Xe]6s24f6\nYear Discovered= 1879'), ('Eu', 'Europium', 'Atomic No= 63\nAtomic Mass= 151.96 u\nAtomic Radius= 233 pm\nState = Solid\nCategory = Lanthanide\nDensity= 5.24 g/cm³\nBoiling Point = 1802 K\nMelting point = 1095 K\nElectronic Configuration = [Xe]6s24f7\nYear Discovered= 1901'), ('Gd', 'Gadolinium', 'Atomic No= 64\nAtomic Mass= 157.2 u\nAtomic Radius= 237 pm\nState = Solid\nCategory = Lanthanide\nDensity= 7.90 g/cm³\nBoiling Point = 3546 K\nMelting point = 1586 K\nElectronic Configuration = [Xe]6s24f75d1\nYear Discovered= 1880'), ('Tb', 'Terbium', 'Atomic No= 65\nAtomic Mass= 158.92 u\nAtomic Radius= 221 pm\nState = Solid\nCategory = Lanthanide\nDensity= 8.23 g/cm³\nBoiling Point = 3503 K\nMelting point = 1629 K\nElectronic Configuration = [Xe]6s24f9\nYear Discovered= 1843'), ('Dy', 'Dysprosium', 'Atomic No= 66\nAtomic Mass= 162.5 u\nAtomic Radius= 229 pm\nState = Solid\nCategory = Lanthanide\nDensity= 8.55 g/cm³\nBoiling Point = 2840 K\nMelting point = 1685 K\nElectronic Configuration = [Xe]6s24f10\nYear Discovered= 1886'), ('Ho', 'Holium', 'Atomic No= 67\nAtomic Mass= 164.93 u\nAtomic Radius= 216 pm\nState = Solid\nCategory = Lanthanide\nDensity= 8.80 g/cm³\nBoiling Point = 2973 K\nMelting point = 1747 K\nElectronic Configuration = [Xe]6s24f11\nYear Discovered= 1878'), ('Er', 'Erbium', 'Atomic No= 68\nAtomic Mass= 167.26 u\nAtomic Radius= 235 pm\nState = Solid\nCategory = Lanthanide\nDensity= 9.07 g/cm³\nBoiling Point = 3141 K\nMelting point = 1802 K\nElectronic Configuration = [Xe]6s24f12\nYear Discovered= 1843'), ('Tm', 'Thulium', 'Atomic No= 69\nAtomic Mass= 168.93 u\nAtomic Radius= 227 pm\nState = Solid\nCategory = Lanthanide\nDensity= 9.32 g/cm³\nBoiling Point = 2223 K\nMelting point = 1818 K\nElectronic Configuration = [Xe]6s24f13\nYear Discovered= 1879'), ('Yb', 'Ytterbium', 'Atomic No= 70\nAtomic Mass= 173 u\nAtomic Radius= 242 pm\nState = Solid\nCategory = Lanthanide\nDensity= 6.90 g/cm³\nBoiling Point = 1469 K\nMelting point = 1092 K\nElectronic Configuration = [Xe]6s24f14\nYear Discovered= 1878'), ('Lu', 'Lutetium', 'Atomic No= 71\nAtomic Mass= 174.96 u\nAtomic Radius= 221 pm\nState = Solid\nCategory = Lanthanide\nDensity= 9.84 g/cm³\nBoiling Point = 3675 K\nMelting point = 1936 K\nElectronic Configuration = [Xe]6s24f145d1\nYear Discovered= 1907') ] r = 11 c = 3 for b in lanthanide: tk.Button(self, text=b[0], width=5, height=4, bg="green2", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) c += 1 if c > 18: c = 1 r += 1 actinide = [ ('>| Th', 'Thorium', 'Atomic No= 90\nAtomic Mass= 232.03 u\nAtomic Radius= 237 pm\nState = Solid\nCategory = Actinide\nDensity= 11.72 g/cm³\nBoiling Point = 5061 K\nMelting point = 2023 K\nElectronic Configuration = [Rn]7s26d2\nYear Discovered= 1828'), ('Pa', 'Protactinium', 'Atomic No= 91\nAtomic Mass= 231.035 u\nAtomic Radius= 243 pm\nState = Solid\nCategory = Actinide\nDensity= 15.37 g/cm³\nBoiling Point = NA\nMelting point = 1845 K\nElectronic Configuration = [Rn]7s25f26d1\nYear Discovered= 1913'), ('U', 'Uranium', 'Atomic No= 92\nAtomic Mass= 238.028 u\nAtomic Radius= 240 pm\nState = Solid\nCategory = Actinide\nDensity= 18.95 g/cm³\nBoiling Point = 4404 K\nMelting point = 1408 K\nElectronic Configuration = [Rn]7s25f36d1\nYear Discovered= 1789'), ('Np', 'Neptunium', 'Atomic No= 93\nAtomic Mass= 237.04 u\nAtomic Radius= 221 pm\nState = Solid\nCategory = Actinide\nDensity= 20.25 g/cm³\nBoiling Point = 4175 K\nMelting point = 917 K\nElectronic Configuration = [Rn]7s25f46d1\nYear Discovered= 1940'), ('Pu', 'Plutonium', 'Atomic No= 94\nAtomic Mass= 244.06 u\nAtomic Radius= 243 pm\nState = Solid\nCategory = Actinide\nDensity= 19.84 g/cm³\nBoiling Point = 3501 K\nMelting point = 913 K\nElectronic Configuration = [Rn]7s25f6\nYear Discovered= 1940'), ('Am', 'Americium', 'Atomic No= 95\nAtomic Mass= 243.06 u\nAtomic Radius= 244 pm\nState = Solid\nCategory = Actinide\nDensity= 13.69 g/cm³\nBoiling Point = 2284 K\nMelting point = 1449 K\nElectronic Configuration = [Rn]7s25f7\nYear Discovered= 1944'), ('Cm', 'Curium', 'Atomic No= 96\nAtomic Mass= 247.07 u\nAtomic Radius= 245 pm\nState = Solid\nCategory = Actinide\nDensity= 13.51 g/cm³\nBoiling Point = 3400 K\nMelting point = 1618 K\nElectronic Configuration = [Rn]7s25f76d1\nYear Discovered= 1944'), ('Bk', 'Berkelium', 'Atomic No= 97\nAtomic Mass= 247.07 u\nAtomic Radius= 244 pm\nState = Solid\nCategory = Actinide\nDensity= 14 g/cm³\nBoiling Point = NA\nMelting point = 1323 K\nElectronic Configuration = [Rn]7s25f9\nYear Discovered= 1949'), ('Cf', 'Californium', 'Atomic No= 98\nAtomic Mass= 251.07 u\nAtomic Radius= 245 pm\nState = Solid\nCategory = Actinide\nDensity= NA\nBoiling Point = NA\nMelting point = 1173 K\nElectronic Configuration = [Rn]7s25f10\nYear Discovered=1950'), ('Es', 'Einsteinium', 'Atomic No= 99\nAtomic Mass= 252.08 u\nAtomic Radius= 245 pm\nState = Solid\nCategory = Actinide\nDensity= NA\nBoiling Point = NA\nMelting point = 1132 K\nElectronic Configuration = [Rn]7s25f11\nYear Discovered= 1952'), ('Fm', 'Fermium', 'Atomic No= 100\nAtomic Mass= 257.09 u\nAtomic Radius= NA\nState = Solid\nCategory = Actinide\nDensity= \nBoiling Point = NA\nMelting point = 1800 K\nElectronic Configuration = [Rn]5f127s2\nYear Discovered= 1952'), ('Md', 'Mendelevium', 'Atomic No= 101\nAtomic Mass= 258.09 u\nAtomic Radius= NA\nState = Solid\nCategory = Actinide\nDensity= NA\nBoiling Point = NA\nMelting point = 1100 K\nElectronic Configuration = [Rn]7s25f13\nYear Discovered= 1955'), ('No', 'Nobelium', 'Atomic No= 102\nAtomic Mass= 259.10 u\nAtomic Radius= NA\nState = Solid\nCategory = Actinide\nDensity= NA\nBoiling Point = NA\nMelting point = 1100K\nElectronic Configuration = [Rn]7s25f14\nYear Discovered= 1957'), ('Lr', 'Lawrencium', 'Atomic No= 103\nAtomic Mass= 266.12 u\nAtomic Radius= NA\nState = Solid\nCategory = Actinide\nDensity= NA\nBoiling Point = NA\nMelting point = 1900 K\nElectronic Configuration = [Rn]7s25f146d1\nYear Discovered= 1961') ] r = 12 c = 3 for b in actinide: tk.Button(self, text=b[0], width=5, height=4, bg="green3", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) c += 1 if c > 18: c = 1 r += 1 # A Reset Button to reset the display values reset = [ ('Reset', 'Click on an element for more info.', '')] r = 12 c = 0 for b in reset: tk.Button(self, text=b[0], width=5, height=4, bg="darkslategrey", fg="white", command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c) r += 1 if r > 7: r = 1 c += 1 self.infoLine = tk.Label(self, text="", justify='left') self.infoLine.grid(row=0, column=0, columnspan=10, rowspan=4) # Replaces Label at the top with the name of whichever element button was pressed def name(self, text): self.topLabel.config(text=text) # Displays information when button is pressed def info(self, text): self.infoLine.config(text=text) # The Main Function def main(): root = tk.Tk() a = App(root) a.grid(row=0, column=0, sticky='nsew') a.mainloop() if __name__ == "__main__": main()
#!/usr/bin/python3 """Square Class""" from models.rectangle import Rectangle class Square(Rectangle): """Square class based on Rectangle""" def __init__(self, size=None, x=0, y=0, id=None): """init method""" super().__init__(size, size, x, y, id) @property def size(self): """size getter""" return self.width @size.setter def size(self, value): self.width = value self.height = value def __str__(self): """returns string message on square stats""" return "[Square] ({}) {}/{} - {}"\ .format(self.id, self.x, self.y, self.size) def update(self, *args, **kwargs): """updates square attributes""" if args is not None and len(args) != 0: atts = ['id', 'size', 'x', 'y'] for i in range(0, len(args)): setattr(self, atts[i], args[i]) else: for key in kwargs.keys(): setattr(self, key, kwargs[key]) def to_dictionary(self): """returns dictionary representation of square""" output = {} output["x"] = self.x output["y"] = self.y output["id"] = self.id output["size"] = self.size return output
#!/usr/bin/python3 """This program devides each element of a matrix""" def matrix_divided(matrix=None, div=None): """function checks all contents of matrix and divides all by div""" error = "matrix must be a matrix (list of lists) of integers/floats" if type(matrix) is not list: raise TypeError(error) if type(matrix[0]) is not list: raise TypeError(error) else: mlen = len(matrix[0]) for x in range(len(matrix)): if type(matrix[x]) is not list: raise TypeError(error) if len(matrix[x]) != mlen: raise TypeError("Each row of the matrix must have the same size") for y in range(len(matrix[x])): if type(matrix[x][y]) not in [int, float]: raise TypeError(error) if type(div) not in [int, float]: raise TypeError("div must be a number") if div == 0: raise ZeroDivisionError("division by zero") result = [] for row in matrix: result.append(list(map(lambda x: round(x / div, 2), row))) return result