text
stringlengths
37
1.41M
#!/usr/bin/env python3 # Chapter 6 -- Creating Containers and Collectibles # ---------------------------------------------------- # .. sectnum:: # # .. contents:: # # Existing Classes # ############################## # namedtuple # ================================ from collections import namedtuple BlackjackCard = namedtuple('BlackjackCard','rank,suit,hard,soft') def card( rank, suit ): if rank == 1: return BlackjackCard( 'A', suit, 1, 11 ) elif 2 <= rank < 11: return BlackjackCard( str(rank), suit, rank, rank ) elif rank == 11: return BlackjackCard( 'J', suit, 10, 10 ) elif rank == 12: return BlackjackCard( 'Q', suit, 10, 10 ) elif rank == 13: return BlackjackCard( 'K', suit, 10, 10 ) c = card( 1, '♠' ) print( c ) class AceCard( BlackjackCard ): __slots__ = () def __new__( self, rank, suit ): return super().__new__( AceCard, 'A', suit, 1, 11 ) c = AceCard( 1, '♠' ) print( c ) try: c.rank= 12 raise Exception( "Shouldn't be able to set attribute." ) except AttributeError as e: print("Expected error:", repr(e)) # deque # ================================ # Example of Deck built from deque. # :: from collections import namedtuple card = namedtuple( 'card', 'rank,suit' ) Suits = '♣', '♦', '♥', '♠' import random from collections import deque class Deck( deque ): def __init__( self, size=1 ): super().__init__() for d in range(size): cards = [ card(r,s) for r in range(13) for s in Suits ] super().extend( cards ) random.shuffle( self ) d= Deck() print( d.pop(), d.pop(), d.pop() ) # ChainMap # ===================== import argparse import json import os parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument( "-c", "--configuration", type=open, nargs='?') parser.add_argument( "-p", "--playerclass", type=str, nargs='?', default="Simple" ) cmdline= parser.parse_args('-p Aggressive'.split()) if cmdline.configuration: config_file= json.load( options.configuration ) options.configuration.close() else: config_file= {} with open("p1_c06_defaults.json") as installation: defaults= json.load( installation ) from collections import ChainMap combined = ChainMap(vars(cmdline), config_file, os.environ, defaults) print( "combined", combined['playerclass'] ) print( "cmdline", cmdline.playerclass ) print( "config_file", config_file.get('playerclass', None) ) print( "defaults", defaults.get('playerclass', None) ) # OrderedDict # ====================== # Some Sample XML # :: source= """ <blog> <topics> <entry ID="UUID98766"><title>first</title><body>more words</body></entry> <entry ID="UUID86543"><title>second</title><body>more words</body></entry> <entry ID="UUID64319"><title>third</title><body>more words</body></entry> </topics> <indices> <bytag> <tag text="#sometag"> <entry IDREF="UUID98766"/> <entry IDREF="UUID86543"/> </tag> <tag text="#anothertag"> <entry IDREF="UUID98766"/> <entry IDREF="UUID64319"/> </tag> </bytag> <bylocation> <location text="Somewhere"> <entry IDREF="UUID98766"/> <entry IDREF="UUID86543"/> </location> <location text="Somewhere Else"> <entry IDREF="UUID98766"/> <entry IDREF="UUID86543"/> </location> </bylocation> </indices> </blog> """ # Parsing # :: from collections import OrderedDict import xml.etree.ElementTree as etree doc= etree.XML( source ) # Parse topics= OrderedDict() # Gather for topic in doc.findall( "topics/entry" ): topics[topic.attrib['ID']] = topic for topic in topics: # Display print( topic, topics[topic].find("title").text ) for tag in doc.findall( "indices/bytag/tag" ): print( tag.attrib['text'] ) for e in tag.findall( "entry" ): print( ' ', e.attrib['IDREF'] ) # The point is to keep the topics in an ordereddict by ID. # We can reference them from other places without scrambling # the original order. # Defaultdict # ===================== from collections import defaultdict messages = defaultdict( lambda: "N/A" ) messages['error1']= 'Full Error Text' messages['other'] used_default= [k for k in messages if messages[k] == "N/A"] # Counter # ================== # A Data Source # :: import random def some_iterator( count= 10000, seed=0 ): random.seed( seed, version=1 ) for i in range(count): yield random.randint( -1, 36 ) # The defaultdict version # :: from collections import defaultdict frequency = defaultdict(int) for k in some_iterator(): frequency[k] += 1 print( frequency ) by_value = defaultdict(list) for k in frequency: by_value[ frequency[k] ].append(k) for freq in sorted(by_value, reverse=True): print( by_value[freq], freq ) print( "expected", 10000//38 ) # The Counter version # :: from collections import Counter frequency = Counter(some_iterator()) print( frequency ) for k,freq in frequency.most_common(): print( k, freq ) print( "expected", 10000//38 ) # Extending Classes # ############################## # Basic Stats formulae # :: import math def mean( outcomes ): return sum(outcomes)/len(outcomes) def stdev( outcomes ): n= len(outcomes) return math.sqrt( n*sum(x**2 for x in outcomes)-sum(outcomes)**2 )/n test_case = [2, 4, 4, 4, 5, 5, 7, 9] assert mean(test_case) == 5 assert stdev(test_case) == 2 print( "Passed Unit Tests" ) # A simple (lazy) stats list class. # :: class Statslist(list): @property def mean(self): return sum(self)/len(self) @property def stdev(self): n= len(self) return math.sqrt( n*sum(x**2 for x in self)-sum(self)**2 )/n tc = Statslist( [2, 4, 4, 4, 5, 5, 7, 9] ) print( tc.mean, tc.stdev ) # Eager Stats List class # :: class StatsList2(list): """Eager Stats.""" def __init__( self, *args, **kw ): self.sum0 = 0 # len(self), sometimes called "N" self.sum1 = 0 # sum(self) self.sum2 = 0 # sum(x**2 for x in self) super().__init__( *args, **kw ) for x in self: self._new(x) def _new( self, value ): self.sum0 += 1 self.sum1 += value self.sum2 += value*value def _rmv( self, value ): self.sum0 -= 1 self.sum1 -= value self.sum2 -= value*value def insert( self, index, value ): super().insert( index, value ) self._new(value) def append( self, value ): super().append( value ) self._new(value) def extend( self, sequence ): super().extend( sequence ) for value in sequence: self._new(value) def pop( self, index=0 ): value= super().pop( index ) self._rmv(value) return value def remove( self, value ): super().remove( value ) self._rmv(value) def __iadd__( self, sequence ): result= super().__iadd__( sequence ) for value in sequence: self._new(value) return result @property def mean(self): return self.sum1/self.sum0 @property def stdev(self): return math.sqrt( self.sum0*self.sum2-self.sum1*self.sum1 )/self.sum0 def __setitem__( self, index, value ): if isinstance(index, slice): start, stop, step = index.indices(len(self)) olds = [ self[i] for i in range(start,stop,step) ] super().__setitem__( index, value ) for x in olds: self._rmv(x) for x in value: self._new(x) else: old= self[index] super().__setitem__( index, value ) self._rmv(old) self._new(value) def __delitem__( self, index ): # Index may be a single integer, or a slice if isinstance(index, slice): start, stop, step = index.indices(len(self)) olds = [ self[i] for i in range(start,stop,step) ] super().__delitem__( index ) for x in olds: self._rmv(x) else: old= self[index] super().__delitem__( index ) self._rmv(old) sl2 = StatsList2( [2, 4, 3, 4, 5, 5, 7, 9, 10] ) print( sl2, sl2.sum0, sl2.sum1, sl2.sum2 ) sl2[2]= 4 print( sl2, sl2.sum0, sl2.sum1, sl2.sum2 ) del sl2[-1] print( sl2, sl2.sum0, sl2.sum1, sl2.sum2 ) sl2.insert( 0, -1 ) print( sl2, sl2.sum0, sl2.sum1, sl2.sum2 ) r= sl2.pop() print( sl2, sl2.sum0, sl2.sum1, sl2.sum2 ) sl2.append( 1 ) print( sl2, sl2.sum0, sl2.sum1, sl2.sum2 ) sl2.extend( [10, 11, 12] ) print( sl2, sl2.sum0, sl2.sum1, sl2.sum2 ) try: sl2.remove( -2 ) except ValueError: pass print( sl2, sl2.sum0, sl2.sum1, sl2.sum2 ) sl2 += [21, 22, 23] print( sl2, sl2.sum0, sl2.sum1, sl2.sum2 ) tc= Statslist([2, 4, 4, 4, 5, 5, 7, 9, 1, 10, 11, 12, 21, 22, 23]) print( "expected", len(tc), "actual", sl2.sum0 ) print( "expected", sum(tc), "actual", sl2.sum1 ) print( "expected", sum(x*x for x in tc), "actual", sl2.sum2 ) assert tc.mean == sl2.mean assert tc.stdev == sl2.stdev sl2a= StatsList2( [2, 4, 3, 4, 5, 5, 7, 9, 10] ) del sl2a[1:3] print( sl2a, sl2a.sum0, sl2a.sum1, sl2a.sum2 ) # Wrapping Classes # ############################## # Stats List Wrapper # :: class StatsList3: def __init__( self ): self._list= list() self.sum0 = 0 # len(self), sometimes called "N" self.sum1 = 0 # sum(self) self.sum2 = 0 # sum(x**2 for x in self) def append( self, value ): self._list.append(value) self.sum0 += 1 self.sum1 += value self.sum2 += value*value def __getitem__( self, index ): return self._list.__getitem__( index ) @property def mean(self): return self.sum1/self.sum0 @property def stdev(self): return math.sqrt( self.sum0*self.sum2-self.sum1*self.sum1 )/self.sum0 sl3= StatsList3() for data in 2, 4, 4, 4, 5, 5, 7, 9: sl3.append(data) print( sl3.mean, sl3.stdev ) # Heading 4 -- Extending Classes # ############################## # Stats Counter # :: import math from collections import Counter class StatsCounter( Counter ): @property def mean( self ): sum0= sum( v for k,v in self.items() ) sum1= sum( k*v for k,v in self.items() ) return sum1/sum0 @property def stdev( self ): sum0= sum( v for k,v in self.items() ) sum1= sum( k*v for k,v in self.items() ) sum2= sum( k*k*v for k,v in self.items() ) return math.sqrt( sum0*sum2-sum1*sum1 )/sum0 @property def median( self ): all= list(sorted(sc.elements())) return all[len(all)//2] @property def median2( self ): mid = sum(self.values())//2 low= 0 for k,v in sorted(self.items()): if low <= mid < low+v: return k low += v sc = StatsCounter( [2, 4, 4, 4, 5, 5, 7, 9] ) print( sc.mean, sc.stdev, sc.most_common(), sc.median, sc.median2 ) # New Sequence from Scratch. # ====================================== # A Binary Searh Tree. # # http://en.wikipedia.org/wiki/Binary_search_tree # # :: import collections.abc import weakref class TreeNode: """.. TODO:: weakref to the tree; tree has the key() function.""" def __init__( self, item, less=None, more=None, parent=None ): self.item= item self.less= less self.more= more if parent != None: self.parent = parent @property def parent( self ): return self.parent_ref() @parent.setter def parent( self, value ): self.parent_ref= weakref.ref(value) def __repr__( self ): return( "TreeNode({item!r},{less!r},{more!r})".format( **self.__dict__ ) ) def find( self, item ): if self.item is None: # Root if self.more: return self.more.find(item) elif self.item == item: return self elif self.item > item and self.less: return self.less.find(item) elif self.item < item and self.more: return self.more.find(item) raise KeyError def __iter__( self ): if self.less: for item in iter(self.less): yield item yield self.item if self.more: for item in iter(self.more): yield item def add( self, item ): if self.item is None: # Root Special Case if self.more: self.more.add( item ) else: self.more= TreeNode( item, parent=self ) elif self.item >= item: if self.less: self.less.add( item ) else: self.less= TreeNode( item, parent=self ) elif self.item < item: if self.more: self.more.add( item ) else: self.more= TreeNode( item, parent=self ) def remove( self, item ): # Recursive search for node if self.item is None or item > self.item: if self.more: self.more.remove(item) else: raise KeyError elif item < self.item: if self.less: self.less.remove(item) else: raise KeyError else: # self.item == item if self.less and self.more: # Two children are present successor = self.more._least() self.item = successor.item successor.remove(successor.item) elif self.less: # One child on less self._replace(self.less) elif self.more: # On child on more self._replace(self.more) else: # Zero children self._replace(None) def _least(self): if self.less is None: return self return self.less._least() def _replace(self,new=None): if self.parent: if self == self.parent.less: self.parent.less = new else: self.parent.more = new if new is not None: new.parent = self.parent class Tree(collections.abc.MutableSet): def __init__( self, iterable=None ): self.root= TreeNode(None) self.size= 0 if iterable: for item in iterable: self.root.add( item ) self.size += 1 def add( self, item ): self.root.add( item ) self.size += 1 def discard( self, item ): try: self.root.more.remove( item ) self.size -= 1 except KeyError: pass def __contains__( self, item ): try: self.root.more.find( item ) return True except KeyError: return False def __iter__( self ): for item in iter(self.root.more): yield item def __len__( self ): return self.size bt= Tree() bt.add( "Number 1" ) print( list( iter(bt) ) ) bt.add( "Number 3" ) print( list( iter(bt) ) ) bt.add( "Number 2" ) print( list( iter(bt) ) ) print( repr(bt.root) ) print( "Number 2" in bt ) print( len(bt) ) bt.remove( "Number 3" ) print( list( iter(bt) ) ) bt.discard( "Number 3" ) # Should be silent try: bt.remove( "Number 3" ) raise Exception( "Fail" ) except KeyError as e: pass # Expected bt.add( "Number 1" ) print( list( iter(bt) ) ) import random for i in range(25): values= ['1','2','3','4','5'] random.shuffle( values ) bt= Tree() for i in values: bt.add(i) assert list( iter(bt) ) == ['1','2','3','4','5'], "IN: {0}, OUT: {1}".format(values,list( iter(bt) )) random.shuffle(values) for i in values: bt.remove(i) values.remove(i) assert list( iter(bt) ) == list(sorted(values)), "IN: {0}, OUT: {1}".format(values,list( iter(bt) )) s1 = Tree( ["Item 1", "Another", "Middle"] ) s2 = Tree( ["Another", "More", "Yet More"] ) print( list( iter(bt) ) ) print( list( iter(bt) ) ) print( list( iter(s1|s2) ) ) # Comparisons # ====================================== # Using a list vs. a set import timeit timeit.timeit( 'l.remove(10); l.append(10)', 'l = list(range(20))' ) timeit.timeit( 'l.remove(10); l.add(10)', 'l = set(range(20))' ) # Using two parallel lists vs. a mapping import timeit timeit.timeit( 'i= k.index(10); v[i]= 0', 'k=list(range(20)); v=list(range(20))' ) timeit.timeit( 'm[10]= 0', 'm=dict(zip(list(range(20)),list(range(20))))' )
''' 题目:取一个整数a从右端开始的4〜7位。 程序分析:可以这样考虑: (1)先使a右移4位。 (2)设置一个低4位全为1,其余全为0的数。可用~(~0<<4) (3)将上面二者进行&运算。 ''' a = int(input('input a number:\n')) b = a >> 4 c=~(~0<<4) d=b&c print("%x"%(d))
''' 题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。 ''' def inp(numbers): for i in range(6): numbers.append(int(input('输入一个数字:\n'))) p = 0 def arr_max(array): max = 0 for i in range(1,len(array) - 1): p = i if array[p] > array[max] : max = p k = max array[0],array[k] = array[k],array[0] def arr_min(array): min = 0 for i in range(1,len(array) - 1): p = i if array[p] < array[min] : min = p l = min array[5],array[l] = array[l],array[5] def outp(numbers): for i in range(len(numbers)): print (numbers[i]) if __name__ == '__main__': array = [] inp(array) # 输入 6 个数字并放入数组 arr_max(array) # 获取最大元素并与第一个元素交换 arr_min(array) # 获取最小元素并与最后一个元素交换 print ('计算结果:') outp(array)
class Node(object): def __init__(self,name=None,value=None): self._name=name self._value=value self._left=None self._right=None class HuffmanTree(object): def __init__(self,char_weights): self.a=[Node(part,char_weights[part]) for part in char_weights] while len(self.a)!=1: self.a.sort(key=lambda node:node._value,reverse=True) c=Node(value=(self.a[-1]._value+self.a[-2]._value)) c._left=self.a.pop(-1) c._right=self.a.pop(-1) self.a.append(c) self.root=self.a[0] re self.b=range(100) def pre(self,tree,length): node=tree if (not node): return elif node._name: print node._name + '\'s encode is :', for i in range(length): print self.b[i], print '\n' return self.b[length]=0 self.pre(node._left,length+1) self.b[length]=1 self.pre(node._right,length+1) def get_code(self): self.pre(self.root,0) if __name__=='__main__': with open("ACGAN.py","r") as f: read_file= f.read() print(str(read_file)) s=str(read_file) resoult={} for i in set(s): resoult[i]=s.count(i) print(resoult) tree=HuffmanTree(resoult) tree.get_code()
#题目:将一个列表的数据复制到另一个列表中。 # #程序分析:使用列表[:]。 a = list(range(10)) b = a[:] print (b)
''' 题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。 ''' class Solution: def LastRemaining_Solution(self, n, m): # write code here # 用列表来模拟环,新建列表range(n),是n个小朋友的编号 if not n or not m: return -1 lis = list(range(n)) i = 0 while len(lis)>1: i = (m-1 + i)%len(lis) # 递推公式 lis.pop(i) return lis[0] a=Solution print(a.LastRemaining_Solution(a, 34, 3)+1)
''' 题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数? 程序分析:请利用数轴来分界,定位。注意定义时需把奖金定义成长整型。 ''' income=int(input("净利润")) arr =[1e6,6e5,4e5,2e5,1e5,0] rat =[0.01,0.015,0.03,0.05,0.075,0.1] r=0 for i in range(6): if income>arr[i]: r=r+(income-arr[i])*rat[i] print((income-arr[i])*rat[i]) income=arr[i] print(r)
import random, string vowels = 'aeiouy' consonants='bcdfghjklmnpqrstvwxz' letters=string.ascii_lowercase letter_input_1=input("What letter do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any letter: ") letter_input_2=input("What letter do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any letter: ") letter_input_3=input("What letter do you want? Enter 'v' for vowels, 'c' for consonants, 'l' for any letter: ") print(letter_input_1+letter_input_2+letter_input_3) #def generator(): #letter1 = random.choice(string.ascii_lowercase) #letter2 = random.choice(string.ascii_lowercase) #letter3 = random.choice(string.ascii_lowercase) #name=letter1+letter2+letter3 #return (name) def generator(): if letter_input_1 == 'v': letter1=random.choice(vowels) elif letter_input_1 == 'c': letter1=random.choice(consonants) elif letter_input_1=='l': letter1=random.choice(letters) else: letter1=letter_input_1 if letter_input_2=='v': letter2=random.choice(vowels) elif letter_input_2=='c': letter2=random.choice(consonants) elif letter_input_2=='l': letter2=random.choice(letters) else: letter2=letter_input_2 if letter_input_3=='v': letter3=random.choice(vowels) elif letter_input_3=='c': letter3=random.choice(consonants) elif letter_input_3=='l': letter3=random.choice(letters) else: letter3=letter_input_3 name=letter1+letter2+letter3 return (name) for i in range(20): print(generator()) #def plot(): #if letter_input_1 == 'v': #l1=random.choice(vowels) #elif letter_input_1 == 'c': #l1=random.choice(consonants) #elif letter_input_1=='l':
a=[] a=[25,40,65,80,55,60] a=[1,"hello",7,5] print(a[2]) print(a[:2]) print(a[2:4]) a[2]=80 a[2:4]=[25,80,55,60] a.append(80) a.extend([25,80,55,60] c=a+b a.extend(b)
name = "Finn" subjects = ["English", "Math", "Science", "Latin", "History"] print("Hello " + name) for i in subjects: print("One of my classes is " + i) countries = ["Germany", "South Africa", "Canada", "Great Britain", "Spain", "France", "Mexico", "China", "Indonesia", "Argentinia"] for i in countries: if i in ["Germany", "South Africa", "Canada", "Great Britain", "Spain"]: print( i + " is a country.") else: print("I have not been to " + i + " but I want to travel there.") movies = [] while True: print("What movie do you like? Type 'end' to quit.") answer = input() if answer == "end": break else: movies.append(answer) for i in movies: print("One of your favourite movies is " + i)
#insertind an element in any desired position class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None self.next=None def append(self,data): n=Node(data) if self.head is None: self.head=n return c=self.head while c.next: c=c.next c.next=n def insert(self,p,data): n=Node(data) c=self.head while c: if c.data==p: n.next=c.next c.next=n return c=c.next print("Do not exist") def display(self): c=self.head while c: print(c.data) c=c.next l=LinkedList() n=int(input("Enter number of elements :")) #loop for taking inputs from the user for i in range(n): data=int(input("Enter element : ")) l.append(data) #taking input from the user to insert data=int(input("Enter element to be inserted : ")) p=int(input("Enter node of the previous position element at which element to be inserted :")) l.insert(p,data) l.display()
class Stack: def __init__(self,size): self.s=[] self.n=size self.i=0 def push(self,data): if self.n>0 : if data not in self.s: self.n-=1 self.s.append(data) else: print('element already exists') else: print('Stack over flow') def isEmpty(self): return len(self.s)==0 def pop(self): if self.isEmpty(): raise Exception('stack under flow') return self.s.pop() def peek(self): return self.s[-1] def size(self): return len(self.s) def specific(self , data): if data in self.s: self.s.remove(data) return else: print('element is not present in the stack') def printStack(self): print(self.s) n=int(input('Enter size : ')) s=Stack(n) print('enter elements :') for i in range(n): s.push(int(input())) p=int(input('enter element you want to pop : ')) print('stack before popping: ') s.printStack() s.specific(p) print('stack after popping: ') s.printStack()
def gates(s): stack=[] temp=0 for i in s: if i=='(': stack.append('(') elif i==')': if stack==[] or stack.pop()!='(': return -1 temp+=1 if stack!=[] or temp==1: return -1 return temp s=input('enter gate notation') print(gates(s))
#Binary Tree with a single node class Node: def __init__(self,data): self.left=None self.right=None self.data=data class BinaryTree: def __init__(self,root): self.root=root def print(self,root): print(root.data) T=BinaryTree(Node(20)) T.print(T.root)
#adding nodes after a given node #class for nodes class Node: #constructor for initialising list def __init__(self,data): self.prev=None self.data=data self.next=None #class for doubly linked list class DoublyLinkedList: #constructor for initialising doubly linked list def __init__(self): self.head=None self.tail=None #function for appending nodes def addNode(self,data): n=Node(data) if self.head is None: self.head=n self.tail=n self.head.prev=None self.tail.next=None return self.tail.next=n n.prev=self.tail self.tail=n #function for adding node after a given node nodes def addNodeAfter(self,key,data): n=Node(data) c=self.head while c.next: if c.data==key: nxt=c.next c.next=n n.prev=c n.next=nxt nxt.prev=n return c=c.next if c.data==key: l.addNode(data) return #function for displaying nodes def display(self): c=self.head while c: print(c.data) c=c.next return l=DoublyLinkedList() l.addNode(1) l.addNode(2) l.addNode(3) l.addNode(4) l.addNodeAfter(4,10) l.display()
""" Python dict model """ from .Model import Model class model(Model): def __init__(self): self.recipes = [{'recipe':'lasagna', 'ingredients':'olives, noodles, sauce, tomatoes', 'reviews':'its okay', 'time_to_cook':'ten minutes'},{'recipe':'peanut butter with jelly', 'ingredients':'bread, peanut, butter, jelly', 'reviews':'its a classic', 'time_to_cook':'ten minutes'}] def select(self): """ Returns recipe list of dictionaries Each dictionary in recipes contains: recipe, ingredients, reviews, time_to_cook :return: List of dictionaries """ return self.recipes def insert(self, recipe, ingredients, reviews, time_to_cook): """ Appends a new list of values representing new message into guestentries :param recipe: String :param ingredients: String :param reviews: String :param time_to_cook: String :return: True """ params = {'recipe':recipe, 'ingredients':ratings, 'reviews':reviews, 'time_to_cook':time_to_cook} self.recipes.append(params) return True
# 1 total = input('What is the total amount for your online shopping?') country = raw_input('Shipping within the US or Canada?') if country == "US": if total <= 50: print "Shipping Costs $6.00" elif total <= 100: print "Shipping Costs $9.00" elif total <= 150: print "Shipping Costs $12.00" else: print "FREE" if country == "Canada": if total <= 50: print "Shipping Costs $8.00" elif total <= 100: print "Shipping Costs $12.00" elif total <= 150: print "Shipping Costs $15.00" else: print "FREE" # 2 name = raw_input('Enter your name?') print "Hello "+name # 3 Fahrenheit = int(input("Enter temperature in Fahrenheit: ")) Celsius = (Fahrenheit - 32) * 5.0/9.0 print "Temperature in Celsius: ",Celsius # 4 hours = input('Enter Hours: ') rate = input ('Enter Rate: ') print "Pay: %f"%(hours*rate) # 5 a = [4,7,3,2,5,9] for c in a: print "Element",c,"position: ",a.index(c) # 6 from string import ascii_lowercase as al dic = {x:i for i, x in enumerate(al, 1)} print dic # 7 my_map = {'a': 1,'b':2} inv_map = {v: k for k, v in my_map.iteritems()} print inv_map # 8 L = ['a', 'b', 'c', 'd'] ite = enumerate(L) print dict(ite)
# Напишите программу, которая обрабатывает результаты IQ-теста из файла “2-in.txt". # В файле лежат несколько строк со значениями(не менее 4-х). # Программа должна вывести в консоль среднее арифметическое по лучшим трем в каждой строке результатам(одно число). a = [] n = [] t = True f = open('2-in.txt') for line in f: a.append(line) f.close() b = []*3*len(a) for i in range(len(a)): s = a[i].split(' ') for k in range(len(s)): if s[k].isdigit() == t: n.append(s[k]) n = map(int, n) n = sorted(n) for h in range(len(n) - 3, len(n)): b.append(n[h]) n = [] print(sum(b)/len(b)) input()
# Напишите программу, содержащую функцию вычисляющую функцию Эйлера для произвольного натурального числа. # Программа должна считывать из файла массив чисел, находить ср.геометрическое значений функции Эйлера чисел массива. def euler(n): a = [] b = [] if n == 1: return 1 for i in range(2, n): if n % i == 0: a.append(i) for k in range(1, n): z = 0 for m in range(len(a)): if k % a[m] == 0: z = 1 if z != 1: b.append(k) return len(b) x = [] f = open('two.txt') for line in f: x.append(line) f.close() for t in range(len(x)): s = x[t].split(' ') s1 = list(map(int, s)) s2 = list(map(euler, s1)) e = 1 for r in range(len(s2)): e *= s2[r] print(e ** 0.5) input()
# -*- coding: utf-8 -*- """ Created on Thu Jun 4 23:10:05 2020 @author: phamk """ class Toyota: def dungxe(self): print("Toyota dừng xe để nạp điện") def nomay(self): print("Toyota nổ máy bằng hộp số tự động") class Porsche: def dungxe(self): print("Porsche dừng xe để bơm xăng") def nomay(self): print("Porsche nổ máy bằng hộp số cơ") # common interface def kiemtra_dungxe(car): car.dungxe() # instantiate objects toyota = Toyota() porsche = Porsche() # passing the object kiemtra_dungxe(toyota) kiemtra_dungxe(porsche)
def computeHCF(x, y): # This function implements the Euclidian algorithm to find H.C.F. of two numbers while(y): x, y = y, x % y return x print("result=",computeHCF(300, 400))
""" A rudimentary implementation of a Trie data structure that will suit our needs for this project. """ class TrieNode: def __init__(self, word, endOfLine=False): self.word = word self.endOfLine = endOfLine self.children = set() """ Insert a node into the trie by adding it to its parent's list of children """ def addChild(self, word): for node in self.children: if node.word == word: return self.children.add(word) """ Search for a particular phrase. If we reach the end of the phrase, then we should return all of the children of the node at the end since they will all be candidate songs. Returns a duple where the first element contains the list of songs (if any) and the second element is the list of words that need to be searched from the root node if no candidate songs were found. """ def searchAtNode(self, words=[], currNode=self): # Iterate through the list of words in order for word in words: for child in currNode.children: # A child node has been found for the current word if child.word = word: foundNode = child # If this word is the end of the phrase, return the songs if foundNode.endOfLine: return (foundNode.children, words[words.index(word):]) break # A match for the word was not found, so the phrase does not exist if currNode == foundNode: return ([], words[words.index(word):])
import numpy as np def menu_admin(): p = input('\nSelamat Datang di Aplikasi penyewaan kendaraan \n1. Tambah Data \n2. List data \n3. Keluar \ninput : ') if p == "1": tambah_data() elif p == "2": print("Status pinjaman kendaraan") for x in arr_B: for i in x: print(i, end = " ") menu_admin() elif p == '3': login() def menu_user(): p = input('\nSelamat Datang di Aplikasi penyewaan kendaraan \n1. Peminjaman \n2. Pengembalian \n3. List Kendaraan \n4. Keluar \ninput : ') if p == '1': peminjaman() elif p == '2': pengembalian() elif p == '3': print("Status pinjaman kendaraan") for x in arr_B: for i in x: print(i, end = " ") print("\n") menu_user() elif p == '4': login() def tambah_data(): kendaraan = input('masukkan nama kendaraan : ') arr_B.insert(-1,[kendaraan, 'tidakdisewa', " "]) print("data sudah masuk\n") print("Status pinjaman kendaraan") for x in arr_B: for i in x: print(i, end = " ") print("\n") menu_admin() def peminjaman(): i = input('Silahkan pinjam kendaraan dari menu kendaraan : ') while True: for c in arr_B: if i == c[0] and c[1] == "tidakdisewa": print("Kendaraan:" + c[0] + "disewa") c[1] = "disewa" menu_user() break elif i == c[0] and c[1] == "disewa": print("kendaraan : "+ c[0] + "telah disewa, lihat kendaraan lain") menu_user() break print("kendaraan tidak ada") menu_user() break def pengembalian(): i = input('Silahkan kembalikan kendaraan yang disewa : ') while True: for c in arr_B: if i == c[0]: print("Kendaraan" + c[0] + "dikembalikan") c[1] = "tidakdisewa" menu_user() break print("kendaraan tidak ada") menu_user() break def login(): arr_A = np.array = ([["Ubay","123","Admin"],["Hakim","123","User"],["Arrafiq","123","User"]]) print("Login") username = input("masukkan username : ") password = input("masukkan password : ") while True: for x in arr_A: if username==x[0] and password==x[1] and x[2]=="Admin": print("\n\n"+ "Selamat datang admin " + x[0]) menu_admin() break elif username==x[0] and password==x[1] and x[2]=="User": print("\n\n"+ "Selamat datang User " + x[0]) menu_user() break print("Salah Akun. \n\n") break arr_B = np.array = ([[]]) login()
# !/usr/bin/env/python # !-*- coding:utf-8 -*- import socket import os import sys HOST = '192.168.78.1' PORT = 8888 def server(ip, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((ip, port)) # 开始监听 s.listen(1) print('Listening at PORT:', port) conn, addr = s.accept() print('Connected by virtual machine:', addr) while True: data = conn.recv(1024).decode() print('received message:', data) # 如果TCP客户端断开连接,则本地Windows服务端也断开连接 if not data: break command = input("Please input the command:").encode() conn.sendall(command) conn.close() s.close() if __name__ == '__main__': server(HOST, PORT)
""" csv_writer_util.py DESCRIPTION: A wrapper and some logic around python's csv library to write out csv files in various formats. TO USE: FILL THIS IN ~~~~ CREDITS: - Logan Davis <ldavis@marlboro.edu> Init date: 3/3/17 | Version: Python 3.6 | DevOS: MacOS 10.11 & <add here> """ import csv class csv_writer_util(object): """ A container objec that wraps some useful functions to write a csv files to disk. """ def csv_write_out(self, outputname, content): """ Writes a file to disk as csv. SIG:(String,List[List[String]]) -> None ARGS: ----------------------------- - outputname: the name the written csv will be given - content: the csv file to write """ output_file = open(outputname, "w") writer = csv.writer(output_file) writer.writerows(content) output_file.close() def writeout_as_json_organized_by_id(self, output_name, content): """ Writes a csv to disk as a JSON file. Each entry is hashed by it's ID column as formatted in the Datini archive csv. SIG:(String,List[List[String]]) -> None ARGS: ----------------------------- - output_name: the name the written csv will be given - content: the csv file to write TODO: - make a better method for getting the id column - make more flexible to hash by any column ID """ json_output = "{\n" header = content[0] body = content[1::] for row in content: json_output = json_output + "\t'" + row[0] + "': { \n" for i in range(1, len(row)): json_output = json_output + "\t\t'" + header[i] + "': '"+row[i] + "',\n" json_output = json_output[:-2:] + "},\n" json_output = json_output + "}" output_file = open(output_name, "w") output_file.write(json_output) output_file.close()
def isArraySorted(A): if len(A) == 1: return True return A[0]<=A[1] and isArraySorted(A[1:]) Array=[45,56,123,78,456,789] if isArraySorted(Array): print("The array is sorted") else: print("The array is not sorted")
n=5 def factorial(num): if num == 1: return 1 return num*factorial(num-1) ans = factorial(n) print('factorial of {0} is {1}'.format(n, ans))
import calendar import datetime from decimal import Decimal class BudgetFunctions: def __init__(self): self.balance = 0.00 self.expenses = {} self.income = {} self.month = 0 self.year = 0 self.income_counter = 0 self.expenses_counter = 0 def print_functions(self): print print "Choose a function:" print print " 1 - Set Checking Balance 7 - Get Balance for Date" print " 2 - Get Checking Balance 8 - Save Data to File" print " 3 - Add Income 9 - Load Data From File" print " 4 - Print Income 10 - Print Available Functions" print " 5 - Add Expense 11 - Print This Month's Calendar" print " 6 - Print Expenses 12 - Exit" print " 13 - Print Month's Budget" print def set_balance(self): amount = raw_input("Enter starting balance for the month: ") self.balance = Decimal(amount) def set_dates(self, year, month): if not year and not month: now = datetime.datetime.now() self.year = now.year self.month = now.month else: self.year = int(year) self.month = int(month) def print_calendar(self): print print(calendar.month(self.year, self.month)) def add_income(self): day = raw_input("What day does this income arrive (dd)?: ") amount = Decimal(raw_input("Amount to add: ")) self.income[self.income_counter] = {'day': day, 'amount': amount} self.income_counter += 1 def print_income(self): if len(self.income) == 0: print "\nNo income entered.\n" print " Day Amount " for k, v in self.income.iteritems(): print " {} ${}".format(v['day'], v['amount']) def add_expense(self): # resp = raw_input("Enter single expense or multiple? (s or m): ") # if resp == 's': day = raw_input("What day for this expense (dd)?: ") amount = Decimal(raw_input("Expense amount: ")) self.expenses[self.expenses_counter] = {'day': day, 'amount': amount} self.expenses_counter += 1 # else: # print "Enter multiple expenses as: [day, amount" def print_expenses(self): print " Day Amount " for k, v in self.expenses.iteritems(): print " {} ${}".format(v['day'], v['amount']) def save_to_file(self): path = raw_input("Please enter the full path to the data file: ") with open(path, 'w+') as f: f.write('[balance]\n') f.write(str(self.balance) + '\n') f.write('[expenses]\n') for i in self.expenses: f.write("{}|{}\n".format(self.expenses[i]['day'], self.expenses[i]['amount'])) f.write('[incomes]\n') for j in self.income: f.write("{}|{}\n".format(self.income[j]['day'], self.income[j]['amount'])) def load_from_file(self): path = raw_input("Please enter the full path to the data file: ") adding_balance = False adding_expenses = False adding_incomes = False ex_cnt = 0 in_cnt = 0 balance = 0 with open(path) as f: for line in f: if '[balance]' in line: adding_balance = True elif '[expenses]' in line: adding_balance = False adding_expenses = True elif '[incomes]' in line: adding_expenses = False adding_incomes = True elif adding_balance: self.balance = Decimal(line) elif adding_expenses: toks = line.split('|') self.expenses[ex_cnt] = {'day': int(toks[0]), 'amount': Decimal(toks[1])} ex_cnt += 1 elif adding_incomes: toks = line.split('|') self.income[in_cnt] = {'day': int(toks[0]), 'amount': Decimal(toks[1])} in_cnt += 1 # update counters self.income_counter = len(self.income) self.expenses_counter = len(self.expenses) def check_for_income_by_day(self, day): all_income = Decimal(0.00) for i in self.income: if day == self.income[i]['day']: all_income += self.income[i]['amount'] return all_income def check_for_expenses_by_day(self, day): all_expenses = Decimal(0.00) for i in self.expenses: if day == self.expenses[i]['day']: all_expenses += self.expenses[i]['amount'] return all_expenses def print_daily_budget(self): running_balance = self.balance # Calendar(6) to start week with Sunday print " day balance income expenses" for d in calendar.Calendar(6).itermonthdays(self.year, self.month): if d == 0: continue inc = self.check_for_income_by_day(d) exp = self.check_for_expenses_by_day(d) running_balance = running_balance + inc running_balance = running_balance - exp print "{}/{:<4} {:>6}{:>8}{:>8} ".format(self.month, d, running_balance, inc, exp) def main(): funcs = BudgetFunctions() end_program = False first_pass = True while not end_program: if first_pass: date = raw_input("Enter the month and year to budget for (yyyy-mm) or leave empty to use current month: ") if date == '': year = None month = None else: tokens = date.split('-') year = tokens[0] month = tokens[1] funcs.set_dates(year, month) funcs.print_functions() first_pass = False choice = int(raw_input("Enter a function, I'll wait here... : ")) if choice == 1: funcs.set_balance() elif choice == 2: print "$" + str(funcs.balance) elif choice == 3: funcs.add_income() elif choice == 4: funcs.print_income() elif choice == 5: funcs.add_expense() elif choice == 6: funcs.print_expenses() elif choice == 7: print "Not implemented yet." elif choice == 8: funcs.save_to_file() elif choice == 9: funcs.load_from_file() elif choice == 10: funcs.print_functions() elif choice == 11: funcs.print_calendar() elif choice == 12: end_program = True elif choice == 13: funcs.print_daily_budget() else: print "No." print "Goodbye!" main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """Convert from one temperature unit to another temperature unit.""" class ConversionError(Exception): pass class InvalidInputError(ConversionError): pass class NotIntegerError(Exception): pass class LowLimitError(Exception): pass def convertCelciusToKelvin(celcius): """Convert Celcius temperature to Kelvin""" if int(celcius) != celcius: raise NotIntegerError('Input must be numeric value') if not celcius > -274: raise LowLimitError('Input is below absolute zero temperature') kelvin = celcius + 273 return kelvin def convertCelciusToFahrenheit(celcius): """Convert Celcius temperature to Fahrenheit""" if int(celcius) != celcius: raise NotIntegerError('Input must be integer value') if not celcius >= -273: raise LowLimitError('Input value must be higher than absolute zero temperature') fahrenheit = ((celcius * 9) / 5) + 32 return fahrenheit def convertKelvinToCelcius(kelvin): """Convert Kelvin to Celcius""" if int(kelvin) != kelvin: raise NotIntegerError('Input value must be an integer') if not kelvin > -1: raise LowLimitError('Input value must be higher than absolute zero temperature') celcius = kelvin - 273 return celcius def convertKelvinToFahrenheit(kelvin): """Convert Kelvin to Celcius.""" if int(kelvin) != kelvin: raise NotIntegerError('Input value must be an integer') if not kelvin > 0: raise LowLimitError('Input value must be higher than absolute zero temperature') fahrenheit = (((kelvin - 273) * 9) / 5) + 32 return fahrenheit def convertFahrenheitToKelvin(fahrenheit): """Convert Fahrenheit to Kelvin""" if int(fahrenheit) != fahrenheit: raise NotIntegerError('Input value must be an integer') if not fahrenheit > -461: raise LowLimitError('Input value must be higher than absolute zero temperature') kelvin = ((fahrenheit - 32) * 5) / 9 + 273 return kelvin def convertFahrenheitToCelcius(fahrenheit): """Convert Fahrenheit to Celcius""" if int(fahrenheit) != fahrenheit: raise NotIntegerError('Input value must be an integer') if not fahrenheit > -461: raise LowLimitError('Input value must be higher than absolute zero temperature') celcius = ((fahrenheit - 32) * 5) / 9 return celcius
# N школьников делят K яблок поровну, не делящийся остаток остается в корзинке. Сколько яблок достанется каждому # школьнику? apples = int(input()) schools = int(input()) print(schools // apples)
# Запишите букву 'A' (латинскую, заглавную) 100 раз подряд. Сдайте на проверку программу, которая выводит эту строчку # (только буквы, без кавычек или пробелов). print('A' * 100, sep='')
# Дано натуральное число. Найдите цифру, стоящую в разряде десятков в его десятичной записи (вторую справа цифру или # 0, если число меньше 10). num = int(input()) print(num // 10 // 10 % 10)
#! usr/bin/env python import string # https://www.hackerrank.com/challenges/funny-string def substract_letters(letter1, letter2): """Given 2 letters, returns the distance absolute between them ==> substract_letters("a", "z") ==> 25 """ alph = string.lowercase idx1 = alph.index(letter1) idx2 = alph.index(letter2) return abs(idx1 - idx2) def is_funny(s): """ Given a string, return if it's funny or not""" reverse = s[::-1] length = len(s) for idx in xrange(1, length): if substract_letters(s[idx], s[idx - 1]) != substract_letters(reverse[idx], reverse[idx - 1]): return False break return True N = int(raw_input()) for _ in xrange(N): s = raw_input() if is_funny(s): print "Funny" else: print "Not Funny"
#!/usr/bin/env python """ You have to make a function that receives an array of strings representing times of day (in the format "HH:MM") and returns the integer number of minutes between the two closest times. 00:00 can be represented as either "00:00" or "24:00", and you can be guaranteed that all other inputs will fall in the range between 00:00 and 24:00. Constraints 2 <= Length of the array <= 1000 """ class Solution(object): def __init__(self, array): self.array = array def adapt(self, string): # takes strings, returns an integer spl_x = string.split(":") return ((60*int(spl_x[0])+int(spl_x[1])) % 1440) def make(self): minutes = [self.adapt(_) for _ in self.array] minutes.sort() print minutes idx = len(minutes) - 1 abs_diff = 2401 bound_check = abs(minutes[-1] % -1440) + minutes[0] while idx > 0: diff = minutes[idx] - minutes[idx - 1] if diff < abs_diff: abs_diff = diff idx -= 1 if bound_check < abs_diff: abs_diff = bound_check print abs_diff x = Solution(['5:12', '12:37', '12:12', '23:54', '23:30', '00:05']) x.make()
#! /usr/bin/env python import pytest """ Write a function that compresses a string and returns it eg. given a string like aaabbcccdff, return a3b2c3d1f2 """ def iter_compress(input_string): """ Takes input string as input, returns compressed string. Iterate over every character in input. if the char same as last counted char - increment its counter in the res array else: add {char}1 to the res array return res array as string """ res = [] for char in input_string: if not res or res[-1][0] != char: res.append("{}1".format(char)) continue if res[-1][0] == char: count_of_last_char = int(res[-1][1]) new_char_n_count = "{}{}".format(char, count_of_last_char + 1) res[-1] = new_char_n_count return "".join(res) def func_compress(input_string, res=[]): """ Recursive solution of compressing a string. Same idea as iterative, instead of iterating over the input_string pass the string and res array into the next recursive func call when string is empty, return contents of the array. """ if input_string == "": outcome = format("".join(res)) return outcome new_char = input_string[0] if not res or new_char != res[-1][0]: res.append("{}1".format(new_char)) else: count_of_last_char = int(res[-1][1]) new_char_n_count = "{}{}".format(new_char, count_of_last_char + 1) res[-1] = new_char_n_count # need to return the recursive function call # otherwise the function returns None return func_compress(input_string[1:], res) def test_iter_compress(): assert iter_compress("aaabbcccdff") == "a3b2c3d1f2" def test_iter_is_func(): x = "aaabbcccdff" assert iter_compress(x) == func_compress(x) if __name__ == '__main__': test iter_compress() test_iter_is_func()
#! usr/bin/env python # https://www.hackerrank.com/challenges/fibonacci-modified first, second, N = map(int,raw_input().split()) def func_fact(idx, first, second): # funky fibonnaci, takes the first 2 values and returns value index idx # T(n) = (T(n-1))**2 + T(n-2) results = [first, second] counter = 2 while counter < idx: next_value = (results[counter-1])**2 + results[counter - 2] results.append(next_value) counter += 1 return results[idx-1] print func_fact(N, first, second)
#! /usr/bin/env python # https://www.hackerrank.com/challenges/taum-and-bday def solve(num_black, num_white, price_black, price_white, price_sub): if price_black + price_sub < price_white: return num_black*price_black + num_white*(price_black + price_sub) elif price_white + price_sub < price_black: return num_white*price_white + num_black*(price_white + price_sub) else: return num_black*price_black + num_white*price_white # hackerrank boilerplate t = int(raw_input().strip()) for a0 in xrange(t): b,w = raw_input().strip().split(' ') b,w = [int(b),int(w)] x,y,z = raw_input().strip().split(' ') x,y,z = [int(x),int(y),int(z)] print solve(b,w,x,y,z)
#! usr/bin/env/python sent = raw_input("") final = "" for idx, char in enumerate(sent): if idx == 0: final += (char.upper()) elif sent[idx - 1] == " ": final += (char.upper()) else: final += (char) print final
#! /usr/bin/env python3 """ Given random 9 letters (possibly with repititions) and a dictionary return the longest possible word """ with open('/usr/share/dict/words') as f: dictionary = [x.lower() for x in f.read.splitlines()]
#! usr/bin/env python # https://www.hackerrank.com/contests/zenhacks/challenges/candy-shop import sys def solve(): """ Requests input, creates a cache array and returns the answer, using the method defined internally """ value = int(raw_input().strip()) coin_values = [1, 2, 5, 10, 20, 50, 100] cache = [[-1 for _ in coin_values] for _ in xrange(value + 1)] def calc_ways_to_make_number_from_coins(NUMBER, start_coin=0): """ Given a value and a start coin value index (default = 0) return the number of ways to make value by combining an infinite number of coins of given values """ # check if the value has been calculated if cache[NUMBER][start_coin] != -1: return cache[NUMBER][start_coin] res = 0 if NUMBER == 0: res = 1 else: for i in xrange(start_coin, len(coin_values)): if coin_values[i] <= NUMBER: res += calc_ways_to_make_number_from_coins( NUMBER - coin_values[i], i) else: break cache[NUMBER][start_coin] = res return res return calc_ways_to_make_number_from_coins(value) print solve()
#importando as bibliotecas necessárias import pandas as pd import xlrd #abrindo o arquivo with open(r"C:\Users\maias\Documents\GitHub\CFB017-SAINT\exercicio_1\WHOPOPTB.xls") as WHOPOPTB: #variável com o arquivo já lido pelo pandas WHOTBDATA = pd.read_excel("WHOPOPTB.xls") #pandas já reconhece que queremos a coluna das mortes por TB TB_deaths = WHOTBDATA["TB deaths"] #utilizando funções básicas do pandas TB_total_deaths = TB_deaths.sum() TB_min_deaths = TB_deaths.min() TB_max_deaths = TB_deaths.max() TB_mean_deaths = TB_deaths.mean() TB_median_deaths = TB_deaths.median() #imprimindo as variáveis print("Exercícios 1 até 5:\n\n",WHOTBDATA) print("\nTB_total_deaths: ",TB_total_deaths) print("\nTB_min_deaths: ",TB_min_deaths) print("\nTB_max_deaths: ",TB_max_deaths) print("\nTB_mean_deaths: ",TB_mean_deaths) print("\nTB_median_deaths: ",TB_median_deaths) #fechando o arquivo WHOPOPTB.close()
import sys from operacoesCompra import * class compraDeProdutos(): def __init__(self, estoque): self._estoque = estoque self._produtos = imprimeProdutos(self._estoque) self._quantidade = imprimeQuantidades(self._estoque) #self._total = calculaTotalCompra(self._estoque) def __str__(self): return f'[Estoque]: {self._estoque},\n[Produtos]: {self._produtos}' def main(): i = True estoque = {} while i: produto = str(input("Nome do produto: ")) preco = float(input("Preço: ")) quant = int(input("Quantidade:")) if produto == '-1' or preco == -1 or quant == -1: i = False else: estoque[produto] = [preco, quant] return estoque estoque = main() compra = compraDeProdutos(estoque)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: omarkawach """ # Import packages import geopandas as gpd import matplotlib.pyplot as plt # Load data neighbourhoods = gpd.read_file("../../shapefiles/ONS/ons.shp") hospitals = gpd.read_file("../../shapefiles/OttawaHospitals/Hospitals.shp") # Plot data fig, ax = plt.subplots() # Make all the ONS polygons gray so that red highlighted polygons pop out more neighbourhoods.plot(ax=ax, facecolor='gray'); # Go through each hospital by geometry for h in hospitals.geometry: # Now go through each neighbourhood by name # We have to intersect using nx or else the interpreter gets mad for n in neighbourhoods.Name: # Find the feature matching the name nx = neighbourhoods[neighbourhoods.Name == n] # See if the neighbourhood intersects with a hospital if(nx.geometry.intersects(h).any() == True): # If a neighbourhood has a hospital, color it's polygon red nx.plot(ax=ax, facecolor='red') plt.tight_layout();
input = "abacabade" #input = "abadabac" def find_not_repeating_character(string): occur_list = [0] * 26 for x in string: if x.isalpha(): occur_list[ord(x) - ord('a')] += 1 min_occur_char_list = [] for i, occur in enumerate(occur_list, start = 0): if occur == 1: min_occur_char_list.append(chr(ord('a') + i)) print(min_occur_char_list) for x in string: if x in min_occur_char_list: return x return '_' result = find_not_repeating_character(input) print(result)
#https://leetcode.com/problems/search-insert-position/description/ #binary search algortihm class Solution: def searchInsert(self, nums: List[int], target: int) -> int: if target not in nums: nums.append(target) #sort values for binary search prepration nums = sorted(nums) #create left and right "anchors" left = 0 right = len(nums) - 1 #this is where dynamic binary search happens through constant cutting and re-evaluation of the list while left <= right: median = (left+right) // 2 if nums[median] == target: return median elif nums[median] < target: left = median + 1 print(left) elif nums[median] > target: right = median - 1
#!/usr/bin/env python # coding: utf-8 # In[7]: def naive_bayes(dataset_location): import pandas as pd import numpy as np from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, accuracy_score # In[8]: dataset = pd.read_csv(dataset_location, encoding = 'latin-1') # dataset.head() #show first 5 rows # In[9]: #Combinig attributes into single list of tuples and using those features create a 2D matrix features = ['name_wt','statuses_count', 'followers_count', 'friends_count','favourites_count','listed_count'] data = dataset.as_matrix(columns = features) # In[ ]: # In[10]: # print("Total instances : ", data.shape[0], "\nNumber of features : ", data.shape[1]) # In[11]: #convert label column into 1D arrray label = np.array(dataset['label']) # label # ## Test and Train Split # # Using 80-20 split # In[12]: X_train, X_test, y_train, y_test = train_test_split(data, label, test_size=0.2, random_state=0) # In[13]: # print("Number of training instances: ", X_train.shape[0]) # In[14]: # print("Number of testing instances: ", X_test.shape[0]) # ## Training the Model # In[15]: # Generate the model nb_model = GaussianNB() # Train the model using the training sets data = X_train label = y_train nb_model.fit(data, label) # ## Testing the Model # # Now our model is ready. We will test our data against given labels. # In[16]: #test set # X_test # In[17]: # nb_model.predict([X_test[1]]) #testing for single instance # In[18]: ''' Now, apply the model to the entire test set and predict the label for each test example ''' y_predict = [] #to store prediction of each test example for test_case in range(len(X_test)): label = nb_model.predict([X_test[test_case]]) #append to the predictions list y_predict.append(np.asscalar(label)) #predictions # In[19]: # y_predict # ## Perormance evaluation of the Model # In[20]: #true negatives is C(0,0), false negatives is C(1,0), false positives is C(0,1) and true positives is C(1,1) conf_matrix = confusion_matrix(y_test, y_predict) # In[21]: #true_negative TN = conf_matrix[0][0] #false_negative FN = conf_matrix[1][0] #false_positive FP = conf_matrix[0][1] #true_positive TP = conf_matrix[1][1] # In[22]: # Recall is the ratio of the total number of correctly classified positive examples divided by the total number of positive examples. # High Recall indicates the class is correctly recognized (small number of FN) recall = (TP)/(TP + FN) # In[23]: # Precision is the the total number of correctly classified positive examples divided by the total number of predicted positive examples. # High Precision indicates an example labeled as positive is indeed positive (small number of FP) precision = (TP)/(TP + FP) # In[24]: fmeasure = (2*recall*precision)/(recall+precision) accuracy = (TP + TN)/(TN + FN + FP + TP) #accuracy_score(y_test, y_predict) # In[25]: print("------ CLASSIFICATION PERFORMANCE OF THE NAIVE BAYES MODEL ------ " "\n Recall : ", (recall*100) ,"%" "\n Precision : ", (precision*100) ,"%" "\n Accuracy : ", (accuracy*100) ,"%" "\n F-measure : ", (fmeasure*100) ,"%" ) if __name__ == "__main__": naive_bayes('data/twitter_dataset.csv')
n2=int(input("enter n")) l=[] c=0 for i in range(n2): a=int(input()) l.append(a) s=set(l) print(list(s))
a=int(input("enter a number")) l=[] for i in range(0,a): b=int(input("enter a number")) l.append(b) l.sort() print(l)
MARS_WEIGHT_MULTIPLIER = 0.38 JUPITER_WEIGHT_MULTIPLIER = 2.34 # used to calculate weights on other planets def weight_on_planets(): weightOnEarth = float(input("What do you weigh on earth? ")) # get user input then convert to float before calculations weightOnMars = weightOnEarth * MARS_WEIGHT_MULTIPLIER weightOnJupiter = weightOnEarth * JUPITER_WEIGHT_MULTIPLIER # get weight on Jupiter and Mars print("\n" + "On Mars you would weigh", weightOnMars, "pounds.\n" + "On Jupiter you would weigh", weightOnJupiter, "pounds.") # print results using \n for new line if __name__ == '__main__': weight_on_planets()
# Write the code that: # Prompts the user to enter a letter in the alphabet: Please enter a letter from the alphabet (a-z or A-Z): # Write the code that determines whether the letter entered is a vowel # Print one of following messages (substituting the letter for x): # The letter x is a vowel # The letter x is a consonant1 vowels = ['a','e','i','o','u'] letter = input('Please enter a letter: ') if len(letter) < 2 and letter.isalpha(): printed = False for v in vowels: if v == letter: print(f'{letter} is a vowel') printed = True break if printed == False: print(f'{letter} is a consonant') else: print('Please enter a valid letter: a-z or A-Z.')
# -*-coding:Utf-8 -* from data import * from functions import * # gettinf scores scores = get_scores() # getting words to be used words = get_words() # printing scores print("Scores: ", scores) #print("list of words: ", words) # getting userName : user = get_userName() #if user doesn't exist, then getting added if user not in scores.keys(): scores[user] = 0 #no points before the first game continueGame = True while continueGame : print("Player {0}: {1} points".format(user, scores[user])) wordToFind = choose_word() #uncomment the following ligne for testing purpose #print("word to find is", wordToFind) triedLetters = [] foundLetters = [] foundWord = get_hiddenWord(wordToFind, foundLetters) nbTries = nbRounds while wordToFind != foundWord and nbTries > 0: print("Word to Find {0} ({1} tries left)".format(foundWord, nbTries)) print("Already tried letters: ", triedLetters) print("") letter = get_letter() if letter in foundLetters or letter in triedLetters: print("You already tried this letter") elif letter in wordToFind: foundLetters.append(letter) print("well done!") else: nbTries -= 1 print("No, that letter is not in that word") triedLetters.append(letter) foundWord = get_hiddenWord(wordToFind, foundLetters) if wordToFind == foundWord: print("Congratulations! you found the word {0}.".format(wordToFind)) else: print("Hanged!, you lose the game...") print("The word was {0}.".format(wordToFind)) #updating user score scores[user] += nbTries #asking to re-play exit = str() #empty string created exit=input("Do you wanna exit now? (y/n)") if exit.lower() == "y": continueGame=False # Game ended, updating scores save_scores(scores) # Displaying user scores : print("You end the game with {0} points.".format(scores[user])) # Prompt exit input("Press ENTER to exit...")
# -*- coding: utf-8 -*- """ Created on Sun Aug 9 12:52:07 2020 @author: tamanna """ #https://www.hackerrank.com/challenges/np-transpose-and-flatten/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen import numpy r, c= input().split() b=[] for i in range(int(r)): p=list(map(int, input().split())) b.append(p) my_array=numpy.array(b) print(numpy.transpose(my_array)) print(my_array.flatten())
# Create a array and find out the sum of the elements import numpy as np a = np.array([1, 2, 3]) print(np.sum(a))
''' Python Program to display the Fibonacci sequence up to nth term using recursive function ''' def fibonacci(num): """ Recursive function to print fibonacci sequence """ return num if num <= 1 else fibonacci(num-1) + fibonacci(num-2) # Number of terms required nterms = 10 print("Fibonacci sequence") for num in range(nterms): print(fibonacci(num))
def hello_func(): pass print(hello_func()) def hello_func(): return "Hello" print(hello_func()) print(hello_func().upper()) def hell_fun(greet, name='Abhishek'): return f'{greet}, {name} Function' print(hell_fun('Hi')) # *args allow arbitrary number of positional argumants # may return a tuple # **kwargs allow arbitrary number of keyword argumants # may return a dictionary with all keyword values def student_info(*args, **kwargs): print(args) print(kwargs) # student_info('Math', 'Art', name='abhishek', age=38) # Output # ('Math', 'Art') # {'name': 'abhishek', 'age':38} courses = ['Math', 'Art'] # We have a list info = {'name': 'abhishek', 'age': 38} # we have a dictionary student_info(*courses, **info) # * and ** unpacks the valuesof the list and dictionary
lista = [] n = int(input("numero: ")) i = 1 while i <= n: num = int(input("numero: ")) lista.append(num) i += 1 print(lista) numMayor = lista[0] i = 1 while i < len(lista): if(lista[i] > numMayor): numMayor = lista[i] i += 1 print("El numero mas alto es: ",numMayor)
n = int(input("N Numero: ")) j = 1 x=1 while j <= n: num = x i = 2 cont = 0 while i < num: if(num % i == 0): cont += 1 i += 1 if(cont == 0): print(num) j += 1 x += 1
# Author: Adam Jeffries # Date: 2/9/2021 # Description: A recursive function named is_subsequence that takes two string parameters # and returns True if the first string is a subsequence of the second string, but returns False otherwise. def is_subsequence(string1, string2): if string1 == "": return True if string2 == "": return False if string1[0] == string2[0]: return is_subsequence(string1[1:], string2[1:]) else: return is_subsequence(string1, string2[1:])
""" A simplistic ASCII-art generator that maps pixel brightness values to a set of ASCII characters. """ from PIL import Image palette = ['#', 'O', 'o', '.', ' '] # Note: we could alternatively invert the image color scheme # before converting to text using PIL.ImageOps.invert() inverted_palette = list(reversed(palette)) def to_char(val, invert=False): """ Map a pixel brightness value in the range [0, 255] to some ASCII representation. """ chars = invert and inverted_palette or palette i = int(val/256 * len(chars)) return chars[i] def _maybe_resize(im, max_w, max_h): w, h = im.size if w > max_w or h > max_h: ratio = min(max_w / w, max_h / h) im = im.resize((int(w * ratio), int(h * ratio))) return im def _normalize_image(im, max_size=None): if max_size: max_w, max_h = max_size im = _maybe_resize(im, max_w, max_h) return im.convert('L') # grayscale def to_ascii(source, max_size=None, invert_colors=False): """ Load image data from source (string buffer, file pointer, etc.) and convert it to an ASCII string representation. """ im = _normalize_image(Image.open(source), max_size) chars = [to_char(val, invert_colors) for val in im.getdata()] w, _ = im.size return '\n'.join([''.join(chars[i:i+w]) for i in range(0, len(chars), w)]) if __name__ == '__main__': from optparse import OptionParser parser = OptionParser() parser.add_option('-i', '--invert', action='store_true', dest='invert') opts, args = parser.parse_args() for path in args: print(to_ascii(path, max_size=(80,80), invert_colors=opts.invert))
## below is the question """ A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10). For example, take 153 (3 digits), which is narcisstic: 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 and 1652 (4 digits), which isn't: 1^4 + 6^4 + 5^4 + 2^4 = 1 + 1296 + 625 + 16 = 1938 The Challenge: Your code must return true or false depending upon whether the given number is a Narcissistic number in base 10. Error checking for text strings or other invalid inputs is not required, only valid positive non-zero integers will be passed into the function. """ def narcissistic(value): n=value sum1=0 l=len(str(value)) for i in range(l): val=value%10 val=val**l sum1=sum1+val value=value//10 # print(sum1,n) if sum1==n: print('true') narcissistic(153)
#1.0 Introduction """ Welcome to Introduction for Health Data Analytics. In this first training task we will get familiarized with Python. Please if you haven't done so already download Anaconda from: https://www.anaconda.com/products/individual. Anaconda comes with a bunch of data science packages already installed which will make things a lot easier for us. First we we learn a little bit about coding in Python, although many of you will already have some experience with this, it won't hurt to refresh your memory! Task 1: List all the Data Types of Python with examples. """ #Text Type: str a = "string" #Numeric Types: int, float, complex b = 1 c = 1.1 d = 1 + 1j #Sequence Types: list, tuple, range e = ["apple", "banana"] f = ("apple", "banana") g = range(6) #Mapping Type: dict cities_council = { "Elgin" : "Moray", "Inverness" : "Highlands", "Aberdeen" : "Aberdeen City"} #Set Types: set, frozenset h = {"apple", "banana"} freeze_f = frozenset(f) #Boolean Type: bool bool_True = True bool_False = False #Binary Types: bytes, bytearray, memoryview """ Task 2: Other useful ways of storing data are in List, Arrays and Tuples. Create one of each and assign them to the variables a, b and c respectively. """ a = ["item1", "item2"] import numpy as np c = ([1,2,3,4], [5,6,7,8]) b = np.array(c) print(b) print(c) """ Task 3: We are also interested in becoming good software developers so we will need to use conditional, loops. Write an statement where the summation of a variable x+1 will be calculated if the value of x is greater than 2. """ x = 2.1 if x > 2: x = x + 1 #Now incorporate a for loop to calculate the value of n(x+1) for n repetitions where n=3. Store each value of the for loop in an array named y. x = 1 n = 3 y = [] for i in range(1,n+1): x = i*(x + 1) y += [x] print(x) print(y) """ Task 4: Finally we will have a look at creating functions. Functions allow us to compute processes much faster without having to repeat lines of code. Using your code from Task 3, create a function called 'my_cool_function', which takes in the value x and will compute the n(x+1) if x is greater than 2 and for n repetitions where values will be stored in an array named y. Your function will return y. """ def my_cool_func(x, n): y = [] if x > 2: for i in range(1,n+1): x = i*(x + 1) y += [x] return y print(my_cool_func(2.1,3)) # That is your first introductory python coding assignment completed! Hopefully you are now comfortable basic coding in Python!
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt x = [1,2,3] y = [3,4,5] x1 = [11,22,33] y1 = [33,44,55] plt.plot(x, y, label="First") plt.plot(x1, y1, label="Second") plt.xlabel('X-axis') plt.ylabel("Y-axis") plt.title("First graph") plt.legend() plt.show()
""" eng_base.py Care English functionality. """ from utils import * vowels = "aieou" consonants = "bcdfghjklmnpqrstvwxyz" def table_match(table, search): for entry in table: if all( (search[i] == entry[i] or search[i] == "any" or entry[i] == "any") for i in range(len(search)) ): return entry[-1] return None
""" eng_base.py Core English functionality. """ from utils import * vowels = "aieou" consonants = "bcdfghjklmnpqrstvwxyz" GR_CASES = { "tense": ( "present", "past", "infinitive", "imperative", "present participle", "past participle" ), "number": ("singular", "plural"), "person": ("first", "second", "third"), "gender": ("masculine", "feminine", "neuter"), "case": ("subjective", "objective", "possessive"), "position": ("modifier", "object"), } def table_match(table, search): for entry in table: if all( (search[i] == entry[i] or search[i] == "any" or entry[i] == "any") for i in range(len(search)) ): return entry[-1] return None def sentence(result): if not result.strip(): return result if result[0].islower(): result = result[0].upper() + result[1:] if result[-1] not in '.?!': result = result + '.' return result
## # Report the name of a shape from its number of sides # # Read the number of sides from the user nsides = int(input("Enter the number of sides: ")) # Determine the name, leaving it empty if an unsupported number of sides was entered name = "" if nsides == 3: name = "triangle" elif nsides == 4: name = "quadrilateral" elif nsides == 5: name = "pentagon" elif nsides == 6: name = "hexagon" elif nsides == 7: name = "heptagon" elif nsides == 8: name = "octagon" elif nsides == 9: name = "nonagon" elif nsides == 10: name = "decagon" # Display an error message or the name of the polygon if name == "": print("That number of sides is not supported by this program.") else: print("That's a", name)
def TowerOfHanoi(n, start, middle, end): if n==1: print("move disk 1 from rod",start,"to rod", middle) else: TowerOfHanoi(n-1,start,end,middle) print("Move disk",str(n),"from rod",start,"to rod",middle) TowerOfHanoi(n-1, end, middle, start) n=4 TowerOfHanoi(n, "A", "B", "C")
""" Dictionary Comprehension Pense no seguinte: Se quisermos criar uma lista, fazemos: lista = [1, 2, 3 , 4] tupla = (1, 2, 3 , 4) # 1, 2, 3, 4 conjunto = {1, 2, 3 , 4} Se quisermos criar um dicionário dicionario = {'a': 1,'b2': 2,'c': 3 ,'d': 4} # SINTAXE {chave: valor for valor in iterável} - lista[valor for valor in iterável] """ # EXEMPLO """ numeros = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} quadrado = {chave: valor ** 2 for chave, valor in numeros.items()} print(quadrado) """ # EXEMPLO """ lista = [1, 2, 3, 4, 5] quadrados = {valor: valor ** 2 for valor in lista} print(quadrados) """ """ chaves = 'abcde' numeros = [1, 2, 3, 4, 5] mistura = {chaves[i]:numeros[i] for i in range(0, len(chaves))} print(mistura) """ # EXEMPLO numeros = [1, 2, 3, 4, 5] res = {num:('par' if num % 2 == 0 else 'impar') for num in numeros} print(res)
filename = input('Type the filename, please: ') action = int(input('What do you want to do? If you want to read the file, type "0". If you want to write numbers into file, type "1" ')) if action == 0: try: reading = open(filename, 'r') for line in reading: print(line, end = '') except IOError: print('Error! There are no files with this name!') else: quantityofnumbers = int(input('How many numbers do you want to write? ')) arrayforwriting = [] for n in range (0, quantityofnumbers): number = float(input('Type number for writing: ')) arrayforwriting.append(str(number)) print('All numbers was written!') writing = open(filename, 'w') for index in arrayforwriting: writing.write(index + '\n') #just comment for test
a = 1 print(type(a)) print(type(1)) print(type(int)) print("----------------------") s = "ann" print(type(s)) print(type(str)) print(type(type)) print('-------------------') class Hello(): pass hello = Hello() print(type(hello)) print(type(Hello)) """ class类是由type这个类生成的对象 ,平常熟悉的对象是由类对象创建的对象,类又是由type创建的 object是所有类都要继承的顶层的类 """ print("-----------------") class Student: pass class myStudent(Student): pass stu = Student() print(type(stu)) mstu = myStudent() print(type(mstu)) print(type(Student)) print(type(myStudent)) print("----------------基类") print(Student.__bases__) print(myStudent.__bases__) print(int.__bases__) print(type.__bases__) print(object.__bases__) print(type(object))
import unittest from CarRental import Car, ElectricCar, PetrolCar, DieselCar, HybridCar, CarFleet # test the car functionality class TestCar(unittest.TestCase): def test_car_fleet(self): car_fleet = CarFleet() self.assertEqual(40, car_fleet.getNumAvailable()) car_fleet.rentCar(5) self.assertEqual(35, car_fleet.getNumAvailable()) car_fleet.returnCar(2) self.assertEqual(37, car_fleet.getNumAvailable()) car_fleet.returnCar(3) self.assertEqual(40, car_fleet.getNumAvailable()) car_fleet.returnCar(3) car_fleet.rentCar(50) if __name__ == '__main__': unittest.main()
from enum import Enum, unique @unique class CheckStatus(Enum): """ Used to identify the status of a security check """ OK = 'OK' """No anomalies detected; everything secure""" WARN = 'WARN' """Anomalies have been detected; not clearly a threat, needs suspicion""" ALERT = 'ALERT' """Threat has been detected""" def increase(self): if self == CheckStatus.OK: return CheckStatus.WARN else: return CheckStatus.ALERT def decrease(self): if self == CheckStatus.ALERT: return CheckStatus.WARN else: return CheckStatus.OK
""" simple program to match to a given string from a given state space """ state_space = [ {'y': 1, 'Y': 1}, {'a': 2, 'A': 2}, {'s': 3, 'S': 3}, {'i': 4, 'I': 4}, {'r': 5, 'R': 5} ] def match_space(str_to_match, state_space): curr_index = 0 for x in str_to_match: if curr_index < len(state_space): curr_index = state_space[curr_index].get(x) else: curr_index = 0 if not curr_index: break if curr_index: print 'Our state space has matched' return True else: print 'Our state space has NOT matched' return False assert match_space(str_to_match='Yasir', state_space=state_space) # should match assert match_space(str_to_match='yasir', state_space=state_space) # should match assert not match_space(str_to_match='aYasir', state_space=state_space) # should not match assert not match_space(str_to_match='Yasira', state_space=state_space) # should not match
a = 7 for i in range(1, a-1): if a % i == 0 : print ("The given number ", i, "is not prime") else: print ("The given number ", i, "is prime")
#*********************************** Python 2 ************************************** def calculabonus( salario, montante): return salario + ((montante * 15)/100) nome = raw_input() salario = float(input()) montante = float(input()) total = calculabonus(salario, montante) print "TOTAL = R$ {0:.2f}".format(total) #*********************************** Python 3 ************************************ def calculabonus( salario, montante): return salario + ((montante * 15)/100) nome = input() salario = float(input()) montante = float(input()) total = calculabonus(salario, montante) print ("TOTAL = R$ {0:.2f}".format(total))
def areadocirculo (raio): return 3.14159 * raio * raio raio = float(input()) area = areadocirculo(raio) print ("A={0:.4f}".format(area) )
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # in place linear algorithm # O(n) time, O(1) space class Solution: # @param A : root node of tree # @return the root node in the tree def flatten(self, head): def is_leaf(node): return node is not None and node.left is None and node.right is None def flatten_recc(node): # flattens tree and returns the tail of a flatten list if is_leaf(node): return node if node.right is None: node.right = node.left node.left = None tail = flatten_recc(node.right) if node.left is not None: left_end = flatten_recc(node.left) left_end.right = node.right node.right = node.left node.left = None return tail flatten_recc(head) return head # The algorithm # # - convert right subtree to a flatten list # - if left is present convert left to a flatten tree. squash the left subtree between current node and the right subtree. (current.right= left, left.tail = right). You need to store the tail (the last leaf node) of the left subtree for that. # # Start from bottom, going up. A single leaf node is already flattened (obviously). if __name__ == '__main__': s = Solution() from data_structures.Tree import * head = TreeNode(3) head.left = TreeNode(47) head.right = TreeNode(4) head = middle_Tree() head.print() print() flattened = s.flatten(head) flattened.print()
#Función: Multiplicar dos numeros sin usar el signo de multiplicación #Entradas: dos numeros que serviran como factores de la multiplicación #Salidas: El valor resultante de la multiplicación #Restriciones def MultiplicarRecursivo(num, factor): if(isinstance(num,int) and (isinstance(factor,int))): if(factor==0): return 0 elif(factor>0): return ((num+num)//2) + MultiplicarRecursivo(num, factor - 1)
#!/usr/bin/python ''' Control USB Missile Launcher using basic GUI. The GUI allows the elevation and azmith angle of the launcher to be set by clicking the directional up, down, left and right buttons. The user clicks the center fire button to launch a missile. 10/29/2020 ''' from tkinter import * import time import threading import worker as worker import queue q = queue.Queue() neutral_color = 'SystemButtonFace' active_color = 'snow3' button_color = 'lightgray' def postMsg(status, motor): msg = { 'status': status, 'motor': motor, } q.put(msg) # up arrow def pressUp(event): return postMsg('go', 'up') def releaseUp(event): return postMsg('stop', 'up') # down arrow def pressDown(event): return postMsg('go', 'down') def releaseDown(event): return postMsg('stop', 'down') # left arrow def pressLeft(event): return postMsg('go', 'left') def releaseLeft(event): return postMsg('stop', 'left') # right arrow def pressRight(event): return postMsg('go', 'right') def releaseRight(event): return postMsg('stop', 'right') # fire def pressFire(event): return postMsg('go', 'fire') # GUI definitions root = Tk() root.title('USB Missile Controller') root.resizable(width=False, height=False) root.geometry('+550+100') root.geometry('600x480') root.configure(bg=neutral_color) # images for buttons in gamefield up_picture = PhotoImage(file='graphics/up.png') down_picture = PhotoImage(file='graphics/down.png') left_picture = PhotoImage(file='graphics/left.png') right_picture = PhotoImage(file='graphics/right.png') fire_picture = PhotoImage(file='graphics/fire.png') # Row 1 ButtonRow1 = Frame(root, bg=neutral_color) ButtonRow1.config(borderwidth=0, relief=FLAT) ButtonUp = Button(ButtonRow1, bg=button_color, activebackground=active_color, height=150, width=150) ButtonUp.pack(side=LEFT) ButtonUp.bind('<ButtonPress-1>', pressUp) ButtonUp.bind('<ButtonRelease-1>', releaseUp) ButtonUp.config(image=up_picture) ButtonRow1.pack(side=TOP, expand=1) # Row2 ButtonRow2 = Frame(root, bg=neutral_color) ButtonRow2.config(borderwidth=0, relief=FLAT) ButtonLeft = Button(ButtonRow2, bg=button_color, activebackground=active_color, height=150, width=150) ButtonLeft.pack(side=LEFT) ButtonLeft.bind('<ButtonPress-1>', pressLeft) ButtonLeft.bind('<ButtonRelease-1>', releaseLeft) ButtonLeft.config(image=left_picture) ButtonFire = Button(ButtonRow2, bg=button_color, activebackground=active_color, height=150, width=150) ButtonFire.pack(side=LEFT) ButtonFire.config(image=fire_picture) ButtonFire.bind('<ButtonPress-1>', pressFire) ButtonRight = Button(ButtonRow2, bg=button_color, activebackground=active_color, height=150, width=150) ButtonRight.pack(side=LEFT) ButtonRight.bind('<ButtonPress-1>', pressRight) ButtonRight.bind('<ButtonRelease-1>', releaseRight) ButtonRight.config(image=right_picture) ButtonRow2.pack(side=TOP, expand=1) # Row 3 ButtonRow3 = Frame(root, bg=neutral_color) ButtonRow3.config(borderwidth=0, relief=FLAT) ButtonDown = Button(ButtonRow3, bg=button_color, activebackground=active_color, height=150, width=150) ButtonDown.pack(side=LEFT) ButtonDown.config(image=down_picture) ButtonDown.bind('<ButtonPress-1>', pressDown) ButtonDown.bind('<ButtonRelease-1>', releaseDown) ButtonRow3.pack(side=TOP, expand=1) thread = worker.Worker(q) thread.start() root.mainloop() thread.running = False thread.join()
# Solicite a un usuario que ingrese sus 8 alimentos favoritos y sus precios # luego realice un gráfico de barras con la información ingresada (recuerde poner título al # gráfico y a sus ejes también recuerde guardar el resultado en un archivo png) import matplotlib.pyplot as plt listaC = [] listaP = [] for i in range (8): alimentos = input ('ingresa tus alimentos favoritos : ') precio = input ('ingresa el valor del alimento :') listaC.append (alimentos) listaP.append (precio) plt.bar(listaC, listaP, width = 0.8, color ='m') plt.title ('alimentos favoritos y sus precios') plt.xlabel ('alimentos') plt.ylabel ('precios') plt.savefig ('alimentosfavoritos.png') plt.show ()
# Pida a un usuario que ingrese sus 5 # snacks favoritos y sus precios luego realice un gráfico de # barras con la información ingresada, recuerde poner titulo al # gráfico y a sus ejes también recuerde guardar el resultado en # un archivo png import matplotlib.pyplot as plt lista1 = [] lista2 = [] for i in range (5): snacks = input ('ingresa tus 5 snacks favoritos : ') lista1.append(snacks) print (lista1) for i in range (5): precios = input ('ingresa el valor por el cual compras los snacks : ') lista2.append (precios) print (lista2) plt.bar (lista1, lista2, width = 0.8, color = 'm') plt.title ('snacks favoritos y sus precios') plt.xlabel ('snacks') plt.ylabel ('precios') plt.savefig ('graficosnacks.png') plt.show()
#-----primer punto----# class Torta (): def __init__ (self, formaentrada, saborentrada, alturaentrada): self.forma = formaentrada self.sabor = saborentrada self.altura = alturaentrada def mostraratributos (self): print (f"""hola, estoy vemdiendo una torta muy linda y deliciosa ya que tiene una forma de {self.forma} y un sabor muy peculiar a {self.sabor}y tiene una altura perfecta de {self.altura} cm """) final = Torta("redonda", "chocolate envinado", 15) final.mostraratributos () #-----segundo punto-----# class Estudiante (): def __init__ (self, edadEntrada, nombreEntrada, idEntrada, carreraEntrada, semestreEntrada): self.edad = edadEntrada self.nombre = nombreEntrada self.id = idEntrada self.carrera = carreraEntrada self.semestre = semestreEntrada def mostraratributos (self): print (f"""hola, como estas? me llamo {self.nombre}, tengo {self.edad} años mi id es {self.id}, estudio {self.carrera} y voy en {self.semestre} semestre, ya casi me graduooo""") final = Estudiante (18, "mariana","1000410396", "ing biomedica", 7) final.mostraratributos () #-----tercer punto-----# class Nutricionista (): def __init__ (edadEntrada,nombreEntrada, universidadEntrada): self.edad = edadEntrada self.nombre = nombreEntrada self.universidad = universidadEntrada def calcularIMC (self, peso, altura): imc = peso/(altura**2) print (f"""mi nombre es {self.nombre} tengo {self.edad} años, me gradue de la universidad {self.universidad}, mi imc calculado es de {imc} """) final = Nutricionista (18, "mariana", "CES") calcularIMC = final.calcularIMC (76,1.67) print (calcularIMC) #-----cuerto punto-----# class Canguro (): def __init__ (self, edadEntrada, idEntrada, nombreEntrada): self.edad = edadEntrada self.id = idEntrada self.nombre = nombreEntrada def saltos (self, saltar): for i in range (saltos): print(f"""este canguro se llama {self.nombre}, tiene {self.edad} años, con id {self.id}, dio {i+1} saltos """) animal = canguro (13, 2888374563, "atto") animal.saltos (15) #-----quinto punto-----#
# Se sabe que un Dólar son 0.82 euros, indique a un usuario que ingrese su # dinero en dólares y su nombre, luego muestre en pantalla el nombre del usuario y cuanto # dinero tiene en dólares (recuerde validar que todos los datos ingresados por el usuario sean # del formato correcto) def conversionEuros (): iscorrectinfo = False while (iscorrectinfo == False): try: nombre = input ('cual es su nombre: ') assert (nombre.isalpha()) iscorrectinfo = True except AssertionError: print ('dato no valido, inenta de nuevo') iscorrectinfo = False while (iscorrectinfo == False): try: dinero = float (input('ingrese una cantidad de dinero en dolares')) iscorrectinfo = True except ValueError: print ('dato no valido, intenta de nuevo') print (f'hola {nombre}, la cantidad de dinero en euros es {dinero*0.82}') conversionEuros() input ('\nPresione una tecla para continuar')
# Problem 3 def convert_to_mandarin(us_num): ''' us_num: a string representing a US number 0 to 99 returns the string mandarin representation of us_num ''' if len(us_num) == 1 or us_num == '10': return trans[us_num] teens = ['11', '12', '13', '14', '15', '16', '17', '18', '19'] if us_num in teens: return 'shi ' + trans[us_num[1]] first = trans[us_num[0]] if us_num[1] == '0': return first + ' shi' else: sec = trans[us_num[1]] return first + ' shi ' + sec # Problem 7 def general_poly(L): """ L, a list of numbers (n0, n1, n2, ... nk) Returns a function, which when applied to a value x, returns the value n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """ def function_generator(L, x): k = len(L) - 1 sum = 0 for number in L: sum += number * x ** k k -= 1 return sum def function(x, l=L): return function_generator(l, x) return function
# secretWord = global lettersGuessed def isWordGuess(secretWord, lettersGuessed): for i in secretWord: if i in lettersGuessed: pass else: return False return True def isLetter(secretWord, lettersGuessed): if guess in lettersGuessed: return ("Oops! You've already guessed that letter: " + getGuessWord(secretWord, lettersGuessed)) elif guess in secretWord: return ('Good guess: ' + getGuessWord(secretWord, lettersGuessed)) else: global guessesLeft guessesLeft -= 1 return ('Oops! That letter is not in my word: ' + getGuessWord(secretWord, lettersGuessed)) def getGuessWord(secretWord, lettersGuessed): lettersGuessed += guess value = '' string = '' for i in secretWord: if i in lettersGuessed: value = i + ' ' else: value = "_ " string = string + value return string def getAvailLetters(lettersGuessed): availLetters = '' for letter in 'abcdefghijklmnopqrstuvwxyz': if letter not in lettersGuessed: availLetters += letter else: pass return (availLetters) def hangman(secretWord): global guessesLeft guessesLeft = 8 lettersGuessed = [] print('Welcome to the game Hangman!') print('I am thinking of a word that is ' + str(len(secretWord)) + ' letters long.') print('-------------') while guessesLeft > 0: availableLetters = getAvailLetters(lettersGuessed) print('You have ' + str(guessesLeft) + ' guesses left.') print('Available letters: ' + (availableLetters)) global guess guess = input('Please guess a letter: ').lower() print(isLetter(secretWord, lettersGuessed)) print('------------') if isWordGuess(secretWord, lettersGuessed) == True: print('Congratulations, you won!') return else: pass
from turtle import * def draw_square(l, c): pencolor(c) for i in range(4): forward(l) left(90) draw_square(50, 'red') mainloop()
# ------------------------------------------------------------------ # Lecture Code # ------------------------------------------------------------------ def merge(A,B): k = len(A) m = len(B) i, j = 0,0 C = [] while i < k and j < m: if A[i] <= B[j]: C.append(A[i]) i = i + 1 else: C.append(B[j]) j = j + 1 if i == k: C += B[j:] else: C += A[i:] return C def merge_sort(A): if len(A) > 1: m = len(A)//2 l = merge_sort(A[:m]) r = merge_sort(A[m:]) return merge(l,r) else: return A # ------------------------------------------------------------------ # HW Code # ------------------------------------------------------------------ # ----------- # HW- Q2a Code # ----------- def Eval(A, n, c): if n==0: return A[0] A[n-1] = A[n-1] + A[n]*c return Eval(A, n-1, c) # ----------- # HW- Q2d Code # ----------- def Eval2(A, n, c): if n==0: return A[0] return Eval2(A[:n/2+1], n/2, c) + c**(n/2)*Eval2(A[(n/2)+1:],n/2,c) # ----------- # HW- Q2e Code # ----------- def power(x, n): if n == 0: return 1 if n%2 == 0: t = power(x,n/2) return t * t else: return x * power(x, n-1) # ----------- # HW- Q4 Code # ----------- comparisons = 0 def min_max(A): global comparisons if len(A) == 1: return (A[0], A[0]) if len(A) == 2: comparisons += 1 if A[0] > A[1]: return (A[1],A[0]) else: return (A[0],A[1]) mid = len(A)//2 mml = min_max(A[:mid]) mmr = min_max(A[mid:]) comparisons += 1 if mml[0] > mmr[0]: _min = mmr[0] else: _min = mml[0] comparisons += 1 if mml[1] < mmr[1]: _max = mmr[1] else: _max = mml[1] return (_min,_max)
age = int(input('How old are you?: ')) retirement = abs(age - 65) if retirement < 10: print("You get to retire soon.") else: print("You have a long time until you can retire!")
from tkinter import * ventana = Tk() # ventana.geometry("500x500") texto = Label(ventana, text="Bienvenido a mi programa") texto.config( fg="white", # color de la letra bg="black", # color background padx=120, # padding x pady=40, # padding Y font=("Arial", 30) ) texto.pack(side=TOP) ######################## texto = Label(ventana, text="Ahora estamos aprendiendo Tkinter") texto.config( fg="white", # color de la letra bg="red", # color background padx=120, # padding x pady=40, # padding Y font=("Arial", 30) ) texto.pack(side=TOP, fill=X, expand=YES) ######################## texto = Label(ventana, text="Mi nombre es Esteban") texto.config( # width=40, height=3, fg="white", bg="orange", padx=10, pady=10, font=("Arial", 30) ) texto.pack(side=LEFT, fill=X, expand=YES) ######################## texto = Label(ventana, text="Sologuren") texto.config( # width=40, height=3, fg="white", bg="green", padx=10, pady=10, font=("Arial", 30) ) texto.pack(side=LEFT, fill=X, expand=YES) ######################## texto = Label(ventana, text="Jamette") texto.config( # width=40, height=3, fg="black", bg="yellow", padx=10, pady=10, font=("Arial", 30) ) texto.pack(side=LEFT, fill=X, expand=YES) ventana.mainloop()
import sys def maxProduct(arr, n): if n < 3: return -1 max_product = -(sys.maxsize - 1) for i in range (0, n - 2): for j in range (i + 1, n - 1): for k in range (j + 1, n): max_product = max ( max_product, arr[i]* arr[j] * arr[k]) return max_product arr = [10, 3, 5, 6, 20] n = len (arr) max = maxProduct (arr, n) if max == -1: print ("No Tripplet Exits") else: print ("Maximum product is", max)
def printArr(arr, n): for i in range (n): print (arr[i], end=" ") def sortArr(arr, n): cnt0 = 0 cnt1 = 0 for i in range (n): if arr[i] == 0: cnt0 += 1 elif arr[i] == 1: cnt1 += 1 i = 0 while (cnt0 > 0): arr[i] = 0 i += 1 cnt0 -= 1 while (cnt1 > 0): arr[i] = 1 i += 1 cnt1 -= 1 printArr(arr, n) arr= [0, 1, 1, 0, 1, 1, 0, 0, 0, 1] n = len (arr) sortArr (arr, n)
def two_way_sort (arr, arr_len): l, r = 0, arr_len - 1 k = 0 while (l < r): while (arr[l] % 2 != 0): l += 1 k += 1 while (arr[r] % 2 == 0 and l < r): r -= 1 if (l < r): arr[l], arr[r] = arr[r], arr[l] odd=arr[:k] even = arr[k:] odd.sort (reverse=True) even.sort () odd.extend (even) return odd arr_len = 6 arr = [1, 3, 2, 7, 5, 4] result = two_way_sort(arr, arr_len) for i in result: print(str(i) + " ")
player1=int(input("enter the score of player 1")) player2=int(input("enter the score of player 2")) player3=int(input("enter the score of player 3")) strike_player1=player1*100/60 strike_player2=player2*100/60 strike_player3=player3*100/60 print("the strike rate of player1",strike_player1) print("the strike rate of player2",strike_player2) print("the strike rate of player3",strike_player3) print("runs scored by player1 for more than 60 balls:",player1*2) print("runs scored by player2 for more than 60 balls:",player2*2) print("runs scored by player3 for more than 60 balls:",player3*2) print("maximum number of six player1 could hit:",player1//6) print("maximum number of six player2 could hit:",player2//6) print("maximum number of six player3 could hit:",player3//6)
#while25 N = int(input('Введите число,большее 1:')) F1 = F2 = 1 while F2 <= N: F1,F2 = F2, F1+F2 print(F2, end='; ') print() print('Первое число Фибоначчи,большее N:', F2)
#if4 a = int(input('Введите первое число:')) b = int(input('Введите второе число:')) c = int(input('Введите третье число:')) x = 0 if a > 0: x+=1 if b > 0: x+=1 if c > 0: x+=1 print('Количество положительных чисел:',x)
''' Created on Sep 8, 2015 @author: ggomarr ''' import nltk # 1 Read up on one of the language technologies mentioned in this section, such as word sense disambiguation, semantic role labeling, question answering, machine translation, named entity detection. Find out what type and quantity of annotated data is required for developing such systems. Why do you think a large amount of data is required? # NA # 2 Using any of the three classifiers described in this chapter, and any features you can think of, # build the best name gender classifier you can. Begin by splitting the Names Corpus into three subsets: # 500 words for the test set, 500 words for the dev-test set, and the remaining 6900 words for the training set. # Then, starting with the example name gender classifier, make incremental improvements. # Use the dev-test set to check your progress. Once you are satisfied with your classifier, # check its final performance on the test set. How does the performance on the test set compare # to the performance on the dev-test set? Is this what you'd expect? def ex02_fe_01(nom): nom = nom.lower() my_features = {} my_features["pos-1"] = nom[-1:] return my_features def ex02_fe_02(nom): nom = nom.lower() my_features = {} my_features["pos-1"] = nom[-1:] my_features["pos-2"] = nom[-2:] my_features["pos-3"] = nom[-3:] return my_features def ex02_fe_02_l(nom): nom = nom.lower() my_features = {} my_features["pos-1"] = nom[-1:] my_features["pos-2"] = nom[-2:] my_features["pos-3"] = nom[-3:] my_features["length"] = len(nom) return my_features def ex02_fe_03(nom): nom = nom.lower() my_features = {} my_features["pos+1"] = nom[:0] my_features["pos+2"] = nom[:1] my_features["pos+3"] = nom[:2] my_features["pos-1"] = nom[-1:] my_features["pos-2"] = nom[-2:] my_features["pos-3"] = nom[-3:] return my_features def ex02_fe_03_l(nom): nom = nom.lower() my_features = {} my_features["pos+1"] = nom[:0] my_features["pos+2"] = nom[:1] my_features["pos+3"] = nom[:2] my_features["pos-1"] = nom[-1:] my_features["pos-2"] = nom[-2:] my_features["pos-3"] = nom[-3:] my_features["length"] = len(nom) return my_features def ex02_fe_04(nom): nom = nom.lower() my_features = {} my_features["pos+1"] = nom[:0] my_features["pos+2"] = nom[:1] my_features["pos+3"] = nom[:2] my_features["pos-1"] = nom[-1:] my_features["pos-2"] = nom[-2:] my_features["pos-3"] = nom[-3:] my_features["length"] = len(nom) vowels=['a','e','i','o','u'] my_features["num_vowels"] = sum( [ nom.count(vowel) for vowel in vowels ] ) return my_features def ex02_fe_05(nom): nom = nom.lower() my_features = {} my_features["pos+1"] = nom[:0] my_features["pos+2"] = nom[:1] my_features["pos+3"] = nom[:2] my_features["pos-1"] = nom[-1:] my_features["pos-2"] = nom[-2:] my_features["pos-3"] = nom[-3:] my_features["length"] = len(nom) vowels=['a','e','i','o','u'] my_features["num_vowels"] = sum( [ nom.count(vowel) for vowel in vowels ] ) my_features["starts_with_vowel"] = nom[0] in vowels return my_features def ex02_construct_data(): return [(name, 'male') for name in nltk.corpus.names.words('male.txt')] + [(name, 'female') for name in nltk.corpus.names.words('female.txt')] def ex02_extract_features(data_set,extractor=ex02_fe_01): return [ (extractor(nom),gender) for (nom,gender) in data_set ] def ex02_split_data(feature_set, fracs=[0.98,0.01,0.01], rnd_seed=False): import random if rnd_seed: random.seed(rnd_seed) random.shuffle(feature_set) num_inst=[ int(len(feature_set)*frac) for frac in fracs ] return feature_set[:num_inst[0]], feature_set[num_inst[0]:num_inst[0]+num_inst[1]], feature_set[num_inst[0]+num_inst[1]:num_inst[0]+num_inst[1]+num_inst[2]] def ex02_train_classifiers(dev,train_classifiers=[True,True,True]): classifiers=[] if train_classifiers[0]: classifiers=classifiers+[ nltk.DecisionTreeClassifier.train(dev) ] if train_classifiers[1]: classifiers=classifiers+[ nltk.NaiveBayesClassifier.train(dev) ] if train_classifiers[2]: classifiers=classifiers+[ nltk.MaxentClassifier.train(dev,max_iter=10) ] return classifiers def ex02_perfs(classifiers,test_set): return [ nltk.classify.accuracy(classifier,test_set) for classifier in classifiers ] def ex02(train_classifiers=[True,True,True], feature_extractor=ex02_fe_03_l, final=False): my_data=ex02_construct_data() my_f_set=ex02_extract_features(my_data, feature_extractor) my_dev, my_dev_test, my_test=ex02_split_data(my_f_set, fracs=[0.5,0.25,0.25], rnd_seed=1) my_classifiers=ex02_train_classifiers(my_dev,train_classifiers) if final: my_perfs=ex02_perfs(my_classifiers,my_test) else: my_perfs=ex02_perfs(my_classifiers,my_dev_test) return my_perfs # ex02(feature_extractor=ex02_fe_01) # [0.7613293051359517, 0.7608257804632427, 0.7613293051359517] # ex02(feature_extractor=ex02_fe_02) # [0.7598187311178247, 0.8001007049345418, 0.7995971802618328] # ex02(feature_extractor=ex02_fe_02_l) # [0.7381671701913394, 0.797583081570997, 0.8006042296072508] # ex02(feature_extractor=ex02_fe_03) # [0.7220543806646526, 0.8207452165156093, 0.8141993957703928] # ex02(feature_extractor=ex02_fe_03_l) # [0.7225579053373615, 0.823766364551863, 0.8141993957703928] # ex02(feature_extractor=ex02_fe_04) # [0.7215508559919436, 0.8101711983887211, 0.8136958710976838] # ex02(feature_extractor=ex02_fe_05) # [0.7215508559919436, 0.81067472306143, 0.8136958710976838] # ex02(feature_extractor=ex02_fe_03_l, final=True) # [0.7185297079556898, 0.8026183282980867, 0.8061430010070494] # 3 The Senseval 2 Corpus contains data intended to train word-sense disambiguation classifiers. # It contains data for four words: hard, interest, line, and serve. Choose one of these four words, # and load the corresponding data: # >>> from nltk.corpus import senseval # >>> instances = senseval.instances('hard.pos') # >>> size = int(len(instances) * 0.1) # >>> train_set, test_set = instances[size:], instances[:size] # Using this dataset, build a classifier that predicts the correct sense tag for a given instance. # See the corpus HOWTO at http://nltk.org/howto for information on using the instance objects # returned by the Senseval 2 Corpus. def ex03_fe_01(context,position): my_features = {} my_features["POS_0"] = context[position][1] return my_features def ex03_fe_02_prev(context,position): my_features = {} my_features["POS_00"] = context[position][1] if position>0: my_features["WRD_-1"] = context[position-1][1] my_features["POS_-1"] = context[position-1][1] else: my_features["WRD_-1"] = "<START>" my_features["POS_-1"] = "<START>" return my_features def ex03_fe_02_next(context,position): my_features = {} my_features["POS_00"] = context[position][1] if position<len(context): my_features["WRD_+1"] = context[position+1][1] my_features["POS_+1"] = context[position+1][1] else: my_features["WRD_+1"] = "<END>" my_features["POS_+1"] = "<END>" return my_features def ex03_fe_03(context,position): my_features = {} my_features["POS_00"] = context[position][1] if position>0: my_features["WRD_-1"] = context[position-1][1] my_features["POS_-1"] = context[position-1][1] else: my_features["WRD_-1"] = "<START>" my_features["POS_-1"] = "<START>" if position<len(context): my_features["WRD_+1"] = context[position+1][1] my_features["POS_+1"] = context[position+1][1] else: my_features["WRD_+1"] = "<END>" my_features["POS_+1"] = "<END>" return my_features def ex03_fe_03_pos(context,position): my_features = {} my_features["POS_00"] = context[position][1] if position>0: my_features["POS_-1"] = context[position-1][1] else: my_features["POS_-1"] = "<START>" if position<len(context): my_features["POS_+1"] = context[position+1][1] else: my_features["POS_+1"] = "<END>" return my_features def ex03_fe_03_pos_pimped(context,position,pos_lst=[-3,-2,-1,0,1,2,3]): my_features = {} for i in pos_lst: if position+i>=0 and position+i<len(context): my_features["POS_{}".format(i)] = context[position+i][1] else: my_features["POS_{}".format(i)] = "<NA>" return my_features def ex03_construct_data(wrd='hard.pos'): return [(instance.context, instance.position, instance.senses[0]) for instance in nltk.corpus.senseval.instances(wrd)] def ex03_extract_features(data_set,extractor=ex03_fe_01): return [ (extractor(context,position),sense) for (context,position,sense) in data_set ] def ex03_split_data(feature_set, fracs=[0.98,0.01,0.01], equilibrate=True, rnd_seed=False): import random if rnd_seed: random.seed(rnd_seed) dev_set, dev_test_set, test_set = [], [], [] if equilibrate: label_set=set([ instance[1] for instance in feature_set ]) feature_set=[ [ instance for instance in feature_set if instance[1]==label ] for label in label_set ] else: feature_set=[ feature_set ] for this_set in feature_set: random.shuffle(this_set) num_inst=[ int(len(this_set)*frac) for frac in fracs ] dev_set=dev_set+this_set[:num_inst[0]] dev_test_set=dev_test_set+this_set[num_inst[0]:num_inst[0]+num_inst[1]] test_set=test_set+this_set[num_inst[0]+num_inst[1]:num_inst[0]+num_inst[1]+num_inst[2]] return dev_set, dev_test_set, test_set def ex03_train_classifiers(dev,train_classifiers=[True,True,True]): classifiers=[] if train_classifiers[0]: classifiers=classifiers+[ nltk.DecisionTreeClassifier.train(dev) ] if train_classifiers[1]: classifiers=classifiers+[ nltk.NaiveBayesClassifier.train(dev) ] if train_classifiers[2]: classifiers=classifiers+[ nltk.MaxentClassifier.train(dev,max_iter=10) ] return classifiers def ex03_perfs(classifiers,test_set): return [ nltk.classify.accuracy(classifier,test_set) for classifier in classifiers ] def ex03(word='hard.pos', train_classifiers=[True,True,True], feature_extractor=ex03_fe_01, equilibrated_split=True, final=False): my_data=ex03_construct_data(word) my_f_set=ex03_extract_features(my_data, feature_extractor) my_dev, my_dev_test, my_test=ex03_split_data(my_f_set, fracs=[0.5,0.25,0.25], equilibrate=equilibrated_split, rnd_seed=1) my_classifiers=ex03_train_classifiers(my_dev,train_classifiers) if final: my_perfs=ex03_perfs(my_classifiers,my_test) else: my_perfs=ex03_perfs(my_classifiers,my_dev_test) return my_perfs # ex03(feature_extractor=ex03_fe_01) # [0.7975970425138632, 0.7975970425138632, 0.7975970425138632] # ex03(feature_extractor=ex03_fe_02_prev) # [0.7985212569316081, 0.7717190388170055, 0.7975970425138632] # ex03(feature_extractor=ex03_fe_02_next) # [0.8012939001848429, 0.7347504621072088, 0.8012939001848429] # ex03(feature_extractor=ex03_fe_03) # [0.8179297597042514, 0.7393715341959335, 0.8179297597042514] # ex03(feature_extractor=ex03_fe_03_pos) # [0.8179297597042514, 0.7532347504621072, 0.8207024029574861] # ex03(feature_extractor=ex03_fe_03_pos, final=True) # [0.8419593345656192, 0.7523105360443623, 0.8317929759704251] # ex03(feature_extractor=ex03_fe_03_pos_pimped) # [0.7504621072088724, 0.788354898336414, 0.8391866913123844] # ex03(feature_extractor=ex03_fe_03_pos_pimped, final=True) # [0.7809611829944547, 0.7985212569316081, 0.8317929759704251] # Trying the classifiers on other words gives 0 accuracy # 4 Using the movie review document classifier discussed in this chapter, generate a list of the 30 features # that the classifier finds to be most informative. Can you explain why these particular features are informative? # Do you find any of them surprising? def ex04_fe_01(vocabulary,description): my_features = {} description=set(description) for vocab in vocabulary: my_features['contains({})'.format(vocab)] = (vocab in description) return my_features def ex04_construct_data(): return [ (list(nltk.corpus.movie_reviews.words(fileid)), evaluation) for evaluation in nltk.corpus.movie_reviews.categories() for fileid in nltk.corpus.movie_reviews.fileids(evaluation) ] def ex04_construct_vocabulary(num=2000): vocab=[ wrd for (wrd,_) in nltk.FreqDist([ word.lower() for word in nltk.corpus.movie_reviews.words() ]).most_common(num) ] return vocab def ex04_extract_features(data_set,vocabulary,extractor=ex04_fe_01): return [ (extractor(vocabulary,description), evaluation) for (description, evaluation) in data_set ] def ex04_split_data(feature_set, fracs=[0.98,0.01,0.01], equilibrate=True, rnd_seed=False): import random if rnd_seed: random.seed(rnd_seed) dev_set, dev_test_set, test_set = [], [], [] if equilibrate: label_set=set([ instance[1] for instance in feature_set ]) feature_set=[ [ instance for instance in feature_set if instance[1]==label ] for label in label_set ] else: feature_set=[ feature_set ] for this_set in feature_set: random.shuffle(this_set) num_inst=[ int(len(this_set)*frac) for frac in fracs ] dev_set=dev_set+this_set[:num_inst[0]] dev_test_set=dev_test_set+this_set[num_inst[0]:num_inst[0]+num_inst[1]] test_set=test_set+this_set[num_inst[0]+num_inst[1]:num_inst[0]+num_inst[1]+num_inst[2]] return dev_set, dev_test_set, test_set def ex04_train_classifiers(dev,train_classifiers=[True,True,True]): classifiers=[] if train_classifiers[0]: classifiers=classifiers+[ nltk.DecisionTreeClassifier.train(dev) ] if train_classifiers[1]: classifiers=classifiers+[ nltk.NaiveBayesClassifier.train(dev) ] if train_classifiers[2]: classifiers=classifiers+[ nltk.MaxentClassifier.train(dev,max_iter=10) ] return classifiers def ex04_perfs(classifiers,test_set): return [ nltk.classify.accuracy(classifier,test_set) for classifier in classifiers ] def ex04(train_classifiers=[False,True,False], feature_extractor=ex04_fe_01, equilibrated_split=True, final=False): my_data=ex04_construct_data() my_vocabulary=ex04_construct_vocabulary() my_f_set=ex04_extract_features(my_data,my_vocabulary,feature_extractor) my_dev, my_dev_test, my_test=ex04_split_data(my_f_set,fracs=[0.5,0.25,0.25],equilibrate=equilibrated_split,rnd_seed=1) my_classifiers=ex04_train_classifiers(my_dev,train_classifiers) if final: my_perfs=ex04_perfs(my_classifiers,my_test) else: my_perfs=ex04_perfs(my_classifiers,my_dev_test) return my_perfs, my_classifiers # (perfs4,my_classifiers4)=ex04() # perfs4 # [0.858] # my_classifiers4[0].show_most_informative_features(30) # Most Informative Features # contains(outstanding) = True pos : neg = 12.2 : 1.0 # contains(lame) = True neg : pos = 7.7 : 1.0 # contains(portrayed) = True pos : neg = 7.2 : 1.0 # contains(fantastic) = True pos : neg = 6.8 : 1.0 # contains(social) = True pos : neg = 5.7 : 1.0 # contains(awful) = True neg : pos = 4.8 : 1.0 # contains(poorly) = True neg : pos = 4.8 : 1.0 # contains(wonderfully) = True pos : neg = 4.7 : 1.0 # contains(damon) = True pos : neg = 4.6 : 1.0 # contains(laughable) = True neg : pos = 4.5 : 1.0 # contains(terrible) = True neg : pos = 4.5 : 1.0 # contains(waste) = True neg : pos = 4.5 : 1.0 # contains(pulp) = True pos : neg = 4.5 : 1.0 # contains(era) = True pos : neg = 4.2 : 1.0 # contains(blame) = True neg : pos = 4.2 : 1.0 # contains(boring) = True neg : pos = 4.2 : 1.0 # contains(superb) = True pos : neg = 4.2 : 1.0 # contains(hanks) = True pos : neg = 4.2 : 1.0 # contains(stupid) = True neg : pos = 4.2 : 1.0 # contains(masterpiece) = True pos : neg = 3.8 : 1.0 # contains(wasted) = True neg : pos = 3.7 : 1.0 # contains(flynt) = True pos : neg = 3.7 : 1.0 # contains(emotions) = True pos : neg = 3.7 : 1.0 # contains(mulan) = True pos : neg = 3.7 : 1.0 # contains(allows) = True pos : neg = 3.6 : 1.0 # contains(unfunny) = True neg : pos = 3.6 : 1.0 # contains(naked) = True neg : pos = 3.6 : 1.0 # contains(badly) = True neg : pos = 3.5 : 1.0 # contains(complex) = True pos : neg = 3.5 : 1.0 # contains(memorable) = True pos : neg = 3.5 : 1.0 # 5 Select one of the classification tasks described in this chapter, such as name gender detection, # document classification, part-of-speech tagging, or dialog act classification. Using the same training # and test data, and the same feature extractor, build three classifiers for the task: a decision tree, # a naive Bayes classifier, and a Maximum Entropy classifier. Compare the performance of the three classifiers # on your selected task. How do you think that your results might be different if you used a different # feature extractor? # Done # 6 The synonyms strong and powerful pattern differently (try combining them with chip and sales). # What features are relevant in this distinction? Build a classifier that predicts when each word should be used. def ex06_fe_01_pos(sent,position,pos_lst=[-3,-2,-1,1,2,3]): my_features = {} for i in pos_lst: if position+i>=0 and position+i<len(sent): my_features["POS_{}".format(i)] = sent[position+i][1] else: my_features["POS_{}".format(i)] = "<NA>" return my_features def ex06_find_all(target,wrds): return [ pos for (pos,wrd) in enumerate(wrds) if wrd==target ] def ex06_construct_data(sents=nltk.corpus.brown.tagged_sents(),targets=['powerful','strong']): data=[] for sent in sents: wrds=[ wrd for (wrd,_) in sent ] for target in targets: target_pos_lst=ex06_find_all(target,wrds) if target_pos_lst: data=data+[ (sent, target_pos, target) for target_pos in target_pos_lst ] return data def ex06_extract_features(data_set,extractor=ex06_fe_01_pos): return [ (extractor(sent,word_pos),word) for (sent,word_pos,word) in data_set ] def ex06_split_data(feature_set, fracs=[0.98,0.01,0.01], equilibrate=True, rnd_seed=False): import random if rnd_seed: random.seed(rnd_seed) dev_set, dev_test_set, test_set = [], [], [] if equilibrate: label_set=set([ instance[1] for instance in feature_set ]) feature_set=[ [ instance for instance in feature_set if instance[1]==label ] for label in label_set ] else: feature_set=[ feature_set ] for this_set in feature_set: random.shuffle(this_set) num_inst=[ int(len(this_set)*frac) for frac in fracs ] dev_set=dev_set+this_set[:num_inst[0]] dev_test_set=dev_test_set+this_set[num_inst[0]:num_inst[0]+num_inst[1]] test_set=test_set+this_set[num_inst[0]+num_inst[1]:num_inst[0]+num_inst[1]+num_inst[2]] return dev_set, dev_test_set, test_set def ex06_train_classifiers(dev,train_classifiers=[True,True,True]): classifiers=[] if train_classifiers[0]: classifiers=classifiers+[ nltk.DecisionTreeClassifier.train(dev) ] if train_classifiers[1]: classifiers=classifiers+[ nltk.NaiveBayesClassifier.train(dev) ] if train_classifiers[2]: classifiers=classifiers+[ nltk.MaxentClassifier.train(dev,max_iter=10) ] return classifiers def ex06_perfs(classifiers,test_set): return [ nltk.classify.accuracy(classifier,test_set) for classifier in classifiers ] def ex06(synonyms=['powerful','strong'], train_classifiers=[True,True,True], feature_extractor=ex06_fe_01_pos, equilibrated_split=True, final=False): my_data=ex06_construct_data(targets=synonyms) my_f_set=ex06_extract_features(my_data,feature_extractor) my_dev, my_dev_test, my_test=ex06_split_data(my_f_set,fracs=[0.50,0.25,0.25],equilibrate=equilibrated_split,rnd_seed=1) my_classifiers=ex06_train_classifiers(my_dev,train_classifiers) if final: my_perfs=ex06_perfs(my_classifiers,my_test) else: my_perfs=ex06_perfs(my_classifiers,my_dev_test) return my_perfs # ex06() # [0.5555555555555556, 0.6349206349206349, 0.6825396825396826] # ex06(final=True) # [0.5873015873015873, 0.6825396825396826, 0.6825396825396826] # 7 The dialog act classifier assigns labels to individual posts, without considering the context # in which the post is found. However, dialog acts are highly dependent on context, # and some sequences of dialog act are much more likely than others. # For example, a ynQuestion dialog act is much more likely to be answered by a yanswer than by a greeting. # Make use of this fact to build a consecutive classifier for labeling dialog acts. # Be sure to consider what features might be useful. See the code for the consecutive classifier # for part-of-speech tags in 1.7 to get some ideas. def ex07_fe_01_pos(posts,position,pos_lst=[-3,-2,-1]): my_features = {} for i in pos_lst: if position+i>=0 and position+i<len(posts): my_features["POS_{}".format(i)] = posts[position+i] else: my_features["POS_{}".format(i)] = "<NA>" return my_features def ex07_construct_data(): return [ post.get('class') for post in nltk.corpus.nps_chat.xml_posts() ] def ex07_extract_features(data_set,extractor=ex07_fe_01_pos): return [ (extractor(data_set,post_pos),data_set[post_pos]) for post_pos in range(len(data_set)) ] def ex07_split_data(feature_set, fracs=[0.98,0.01,0.01], equilibrate=True, rnd_seed=False): import random if rnd_seed: random.seed(rnd_seed) dev_set, dev_test_set, test_set = [], [], [] if equilibrate: label_set=set([ instance[1] for instance in feature_set ]) feature_set=[ [ instance for instance in feature_set if instance[1]==label ] for label in label_set ] else: feature_set=[ feature_set ] for this_set in feature_set: random.shuffle(this_set) num_inst=[ int(len(this_set)*frac) for frac in fracs ] dev_set=dev_set+this_set[:num_inst[0]] dev_test_set=dev_test_set+this_set[num_inst[0]:num_inst[0]+num_inst[1]] test_set=test_set+this_set[num_inst[0]+num_inst[1]:num_inst[0]+num_inst[1]+num_inst[2]] return dev_set, dev_test_set, test_set def ex07_train_classifiers(dev,train_classifiers=[True,True,True]): classifiers=[] if train_classifiers[0]: classifiers=classifiers+[ nltk.DecisionTreeClassifier.train(dev) ] if train_classifiers[1]: classifiers=classifiers+[ nltk.NaiveBayesClassifier.train(dev) ] if train_classifiers[2]: classifiers=classifiers+[ nltk.MaxentClassifier.train(dev,max_iter=10) ] return classifiers def ex07_perfs(classifiers,test_set): return [ nltk.classify.accuracy(classifier,test_set) for classifier in classifiers ] def ex07(train_classifiers=[True,True,True], feature_extractor=ex07_fe_01_pos, equilibrated_split=True, final=False): my_data=ex07_construct_data() my_f_set=ex07_extract_features(my_data,feature_extractor) my_dev, my_dev_test, my_test=ex07_split_data(my_f_set,fracs=[0.50,0.25,0.25],equilibrate=equilibrated_split,rnd_seed=1) my_classifiers=ex07_train_classifiers(my_dev,train_classifiers) if final: my_perfs=ex07_perfs(my_classifiers,my_test) else: my_perfs=ex07_perfs(my_classifiers,my_dev_test) return my_perfs # ex07() # [0.28148710166919577, 0.3319423368740516, 0.3334597875569044] # ex07(final=True) # [0.2071320182094082, 0.3216995447647951, 0.3311836115326252] # 8 Word features can be very useful for performing document classification, # since the words that appear in a document give a strong indication about what its semantic content is. # However, many words occur very infrequently, and some of the most informative words in a document # may never have occurred in our training data. One solution is to make use of a lexicon, # which describes how different words relate to one another. # Using WordNet lexicon, augment the movie review document classifier presented in this chapter # to use features that generalize the words that appear in a document, making it more likely # that they will match words found in the training data. def ex08_fe_01(vocabulary,description): my_features = {} synset_list=[] for word in description: synset_list=synset_list + nltk.corpus.wordnet.synsets(word.lower()) description=set(synset_list) for vocab in vocabulary: my_features['contains({})'.format(vocab)] = (vocab in description) return my_features def ex08_construct_data(): return [ (list(nltk.corpus.movie_reviews.words(fileid)), evaluation) for evaluation in nltk.corpus.movie_reviews.categories() for fileid in nltk.corpus.movie_reviews.fileids(evaluation) ] def ex08_construct_syn_vocabulary(num=2000): vocab=[ wrd for (wrd,_) in nltk.FreqDist([ word.lower() for word in nltk.corpus.movie_reviews.words() ]).most_common(num) ] synset_list=[] for word in vocab: synset_list=synset_list + nltk.corpus.wordnet.synsets(word.lower()) return list(set(synset_list)) def ex08_extract_features(data_set,vocabulary,extractor=ex08_fe_01): return [ (extractor(vocabulary,description), evaluation) for (description, evaluation) in data_set ] def ex08_split_data(feature_set, fracs=[0.98,0.01,0.01], equilibrate=True, rnd_seed=False): import random if rnd_seed: random.seed(rnd_seed) dev_set, dev_test_set, test_set = [], [], [] if equilibrate: label_set=set([ instance[1] for instance in feature_set ]) feature_set=[ [ instance for instance in feature_set if instance[1]==label ] for label in label_set ] else: feature_set=[ feature_set ] for this_set in feature_set: random.shuffle(this_set) num_inst=[ int(len(this_set)*frac) for frac in fracs ] dev_set=dev_set+this_set[:num_inst[0]] dev_test_set=dev_test_set+this_set[num_inst[0]:num_inst[0]+num_inst[1]] test_set=test_set+this_set[num_inst[0]+num_inst[1]:num_inst[0]+num_inst[1]+num_inst[2]] return dev_set, dev_test_set, test_set def ex08_train_classifiers(dev,train_classifiers=[True,True,True]): classifiers=[] if train_classifiers[0]: classifiers=classifiers+[ nltk.DecisionTreeClassifier.train(dev) ] if train_classifiers[1]: classifiers=classifiers+[ nltk.NaiveBayesClassifier.train(dev) ] if train_classifiers[2]: classifiers=classifiers+[ nltk.MaxentClassifier.train(dev,max_iter=10) ] return classifiers def ex08_perfs(classifiers,test_set): return [ nltk.classify.accuracy(classifier,test_set) for classifier in classifiers ] def ex08(train_classifiers=[False,True,False], feature_extractor=ex08_fe_01, equilibrated_split=True, final=False): my_data=ex08_construct_data() my_syn_vocabulary=ex08_construct_syn_vocabulary() my_f_set=ex08_extract_features(my_data,my_syn_vocabulary,feature_extractor) my_dev, my_dev_test, my_test=ex08_split_data(my_f_set,fracs=[0.5,0.25,0.25],equilibrate=equilibrated_split,rnd_seed=1) my_classifiers=ex08_train_classifiers(my_dev,train_classifiers) if final: my_perfs=ex08_perfs(my_classifiers,my_test) else: my_perfs=ex08_perfs(my_classifiers,my_dev_test) return my_perfs, my_classifiers # (perfs8,my_classifiers8)=ex08() # perfs8 # [0.802] # 9 The PP Attachment Corpus is a corpus describing prepositional phrase attachment decisions. # Each instance in the corpus is encoded as a PPAttachment object: # # >>> from nltk.corpus import ppattach # >>> ppattach.attachments('training') # [PPAttachment(sent='0', verb='join', noun1='board', # prep='as', noun2='director', attachment='V'), # PPAttachment(sent='1', verb='is', noun1='chairman', # prep='of', noun2='N.V.', attachment='N'), # ...] # >>> inst = ppattach.attachments('training')[1] # >>> (inst.noun1, inst.prep, inst.noun2) # ('chairman', 'of', 'N.V.') # Select only the instances where inst.attachment is N: # # >>> nattach = [inst for inst in ppattach.attachments('training') # ... if inst.attachment == 'N'] # Using this sub-corpus, build a classifier that attempts to predict which preposition is used # to connect a given pair of nouns. For example, given the pair of nouns "team" and "researchers," # the classifier should predict the preposition "of". # See the corpus HOWTO at http://nltk.org/howto for more information on using the PP attachment corpus. def ex09_fe_01_verb(inst): my_features = {} my_features['verb'] = inst[0] return my_features def ex09_fe_01_noun1(inst): my_features = {} my_features['noun1'] = inst[1] return my_features def ex09_fe_01_noun2(inst): my_features = {} my_features['noun2'] = inst[2] return my_features def ex09_fe_02_nouns(inst): my_features = {} my_features['noun1'] = inst[1] my_features['noun2'] = inst[2] return my_features def ex09_fe_03_all(inst): my_features = {} my_features['verb'] = inst[0] my_features['noun1'] = inst[1] my_features['noun2'] = inst[2] return my_features def ex09_construct_data(): return [ inst for inst in nltk.corpus.ppattach.attachments('training') if inst.attachment == 'N'] def ex09_extract_features(data_set,extractor=ex09_fe_01_verb): return [ (extractor([ inst.verb, inst.noun1, inst.noun2 ]), inst.prep) for inst in data_set ] def ex09_split_data(feature_set, fracs=[0.98,0.01,0.01], equilibrate=True, rnd_seed=False): import random if rnd_seed: random.seed(rnd_seed) dev_set, dev_test_set, test_set = [], [], [] if equilibrate: label_set=set([ instance[1] for instance in feature_set ]) feature_set=[ [ instance for instance in feature_set if instance[1]==label ] for label in label_set ] else: feature_set=[ feature_set ] for this_set in feature_set: random.shuffle(this_set) num_inst=[ int(len(this_set)*frac) for frac in fracs ] dev_set=dev_set+this_set[:num_inst[0]] dev_test_set=dev_test_set+this_set[num_inst[0]:num_inst[0]+num_inst[1]] test_set=test_set+this_set[num_inst[0]+num_inst[1]:num_inst[0]+num_inst[1]+num_inst[2]] return dev_set, dev_test_set, test_set def ex09_train_classifiers(dev,train_classifiers=[True,True,True]): classifiers=[] if train_classifiers[0]: classifiers=classifiers+[ nltk.DecisionTreeClassifier.train(dev) ] if train_classifiers[1]: classifiers=classifiers+[ nltk.NaiveBayesClassifier.train(dev) ] if train_classifiers[2]: classifiers=classifiers+[ nltk.MaxentClassifier.train(dev,max_iter=10) ] return classifiers def ex09_perfs(classifiers,test_set): return [ nltk.classify.accuracy(classifier,test_set) for classifier in classifiers ] def ex09(train_classifiers=[True,True,True], feature_extractor=ex09_fe_01_verb, equilibrated_split=True, final=False): my_data=ex09_construct_data() my_f_set=ex09_extract_features(my_data,feature_extractor) my_dev, my_dev_test, my_test=ex09_split_data(my_f_set,fracs=[0.5,0.25,0.25],equilibrate=equilibrated_split,rnd_seed=1) my_classifiers=ex09_train_classifiers(my_dev,train_classifiers) if final: my_perfs=ex09_perfs(my_classifiers,my_test) else: my_perfs=ex09_perfs(my_classifiers,my_dev_test) return my_perfs, my_classifiers # (perfs,_)=ex09(feature_extractor=ex09_fe_01_verb) # perfs # [0.3854437430375046, 0.5016709988860008, 0.38024507983661343] # (perfs,_)=ex09(feature_extractor=ex09_fe_01_noun1) # perfs # [0.506869662086892, 0.5989602673598218, 0.5087263275157816] # (perfs,_)=ex09(feature_extractor=ex09_fe_01_noun2) # perfs # [0.35536576308949125, 0.5224656516895655, 0.35425176383215745] # (perfs,_)=ex09(feature_extractor=ex09_fe_02_nouns) # perfs # [0.46193835870776084, 0.5785369476420349, 0.5384329743780171] # (perfs,_)=ex09(feature_extractor=ex09_fe_03_all) # perfs # [0.47307835128109915, 0.558113627924248, 0.5692536204975863] # (perfs, _)=ex09(feature_extractor=ex09_fe_01_noun1,final=True) # perfs # [0.49832900111399925, 0.590790939472707, 0.4994430003713331] # 10 Suppose you wanted to automatically generate a prose description of a scene, # and already had a word to uniquely describe each entity, such as the jar, # and simply wanted to decide whether to use in or on in relating various items, # e.g. the book is in the cupboard vs the book is on the shelf. # Explore this issue by looking at corpus data; writing programs as needed. # # a. in the car versus on the train # b. in town versus on campus # c. in the picture versus on the screen # d. in Macbeth versus on Letterman def ex10_fe_01_word(sent,pos_prep,pos_noun,pos_lst=[-1]): my_features = {} my_features['WORD_noun']=sent[pos_noun][0] return my_features def ex10_fe_01_word_and_pos(sent,pos_prep,pos_noun,pos_lst=[-1]): my_features = {} my_features['WORD_noun']=sent[pos_noun][0] my_features['POS_noun']=sent[pos_noun][1] return my_features def ex10_fe_02_pos(sent,pos_prep,pos_noun,pos_lst=[-1]): my_features = {} for i in pos_lst: if pos_prep+i>=0 and pos_prep+i<len(sent): my_features["POS_{}".format(i)] = sent[pos_prep+i][1] else: my_features["POS_{}".format(i)] = "<NA>" my_features['WORD_noun']=sent[pos_noun][0] my_features['POS_noun']=sent[pos_noun][1] return my_features def ex10_fe_02_word(sent,pos_prep,pos_noun,pos_lst=[-1]): my_features = {} for i in pos_lst: if pos_prep+i>=0 and pos_prep+i<len(sent): my_features["WORD_{}".format(i)] = sent[pos_prep+i][0] else: my_features["WORD_{}".format(i)] = "<NA>" my_features['WORD_noun']=sent[pos_noun][0] my_features['POS_noun']=sent[pos_noun][1] return my_features def ex10_find_noun(sent,target_pos,valid_pos_lst=['NN','NP'],splitters='(),.-:?!',search_range=5): pos_noun=None if target_pos+1<len(sent): for i in range(target_pos+1,min(target_pos+1+search_range,len(sent))): if sum([ valid_pos in sent[i][1] for valid_pos in valid_pos_lst ]): pos_noun=i break if sent[i][1] in splitters: break return pos_noun def ex10_find_all(target,sent): wrds=[ wrd for (wrd,_) in sent ] candidate_pos_list=[ [pos,ex10_find_noun(sent,pos)] for (pos,wrd) in enumerate(wrds) if wrd==target ] return [ inst for inst in candidate_pos_list if inst[1] ] def ex10_construct_data(sents=nltk.corpus.brown.tagged_sents(),targets=['on','in']): data=[] for sent in sents: for target in targets: target_pos_lst=ex10_find_all(target,sent) if target_pos_lst: data=data+[ (sent, target_pos[0], target_pos[1], target) for target_pos in target_pos_lst ] return data def ex10_extract_features(data_set,extractor=ex10_fe_01_word): return [ (extractor(sent,prep_pos,noun_pos),prep) for (sent,prep_pos,noun_pos,prep) in data_set ] def ex10_split_data(feature_set, fracs=[0.98,0.01,0.01], equilibrate=True, rnd_seed=False): import random if rnd_seed: random.seed(rnd_seed) dev_set, dev_test_set, test_set = [], [], [] if equilibrate: label_set=set([ instance[1] for instance in feature_set ]) feature_set=[ [ instance for instance in feature_set if instance[1]==label ] for label in label_set ] else: feature_set=[ feature_set ] for this_set in feature_set: random.shuffle(this_set) num_inst=[ int(len(this_set)*frac) for frac in fracs ] dev_set=dev_set+this_set[:num_inst[0]] dev_test_set=dev_test_set+this_set[num_inst[0]:num_inst[0]+num_inst[1]] test_set=test_set+this_set[num_inst[0]+num_inst[1]:num_inst[0]+num_inst[1]+num_inst[2]] return dev_set, dev_test_set, test_set def ex10_train_classifiers(dev,train_classifiers=[True,True,True]): classifiers=[] if train_classifiers[0]: classifiers=classifiers+[ nltk.DecisionTreeClassifier.train(dev) ] if train_classifiers[1]: classifiers=classifiers+[ nltk.NaiveBayesClassifier.train(dev) ] if train_classifiers[2]: classifiers=classifiers+[ nltk.MaxentClassifier.train(dev,max_iter=10) ] return classifiers def ex10_perfs(classifiers,test_set): return [ nltk.classify.accuracy(classifier,test_set) for classifier in classifiers ] def ex10(preps=['on','in'], train_classifiers=[True,True,True], feature_extractor=ex10_fe_01_word, equilibrated_split=True, final=False): my_data=ex10_construct_data(targets=preps) my_f_set=ex10_extract_features(my_data,feature_extractor) my_dev, my_dev_test, my_test=ex10_split_data(my_f_set,fracs=[0.50,0.25,0.25],equilibrate=equilibrated_split,rnd_seed=1) my_classifiers=ex10_train_classifiers(my_dev,train_classifiers) if final: my_perfs=ex10_perfs(my_classifiers,my_test) else: my_perfs=ex10_perfs(my_classifiers,my_dev_test) return my_perfs, my_classifiers # (perfs,_)=ex10(feature_extractor=ex10_fe_01_word) # perfs # [0.7873387644263408, 0.7954854039375424, 0.6961982348947726] # (perfs,_)=ex10(feature_extractor=ex10_fe_01_word_and_pos) # perfs # [0.7871690427698574, 0.7953156822810591, 0.7951459606245757] # (perfs,_)=ex10(feature_extractor=ex10_fe_02_pos) # perfs # [0.7922606924643585, 0.787847929395791, 0.7927698574338086] # (perfs,_)=ex10(feature_extractor=ex10_fe_02_word) # perfs # [0.7854718262050238, 0.7829260013577732, 0.8185675492192804] # (perfs,_)=ex10(feature_extractor=ex10_fe_02_word, final=True) # perfs # [0.7881873727087576, 0.7875084860828242, 0.814663951120163] # This is cheating, I know, I know... # (perfs,_)=ex10(feature_extractor=ex10_fe_01_word, final=True) # perfs # [0.7898845892735913, 0.7970128988458928, 0.6887304820095044]
#This code shows how if you continue to sum the halves it never hits 1 but rather .99.... n=0 x=.5 n+=.5 print(n) import time while n<1: time.sleep(.5); n*=0.5 print(n , 'half of previous') if n<1: x+=n print(x , "Is the Total Sum") continue if n>=1.0: print("breaking") break
you = "today" if you == "": robot_brain = "I can't hear you, try again" elif you == "hello": robot_brain = "hello ted" elif you == "today": robot_brain = "chu nhat" else: robot_brain = "I'm fine thank you, and you" print(robot_brain)
################ # Sebastian Scheel - @sebastianscheel # Plantilla de ejercicio # UNRN Andina - Introducción a la Ingenieria en Computación ################ from soporte import minimo,maximo lista=[] cantidad_valores=int(input("cantidad de valores de la lista: ")) for i in range (cantidad_valores): lista.append(input("ingresar valor:")) print(f"esta es la lista: ",lista) maximo(lista) minimo(lista)
# The 'continue' keyword, used within a loop, skips the remaining code in the loop block, instead proceeding on to the next iteration. In the following example, 'continue' is leveraged to print only the positive numbers stored in a list. big_number_list = [1, 2, -1, 4, -5, 5, 2, -9] for i in big_number_list: if i < 0: continue print(i)
''' Review 1: Create a string object that stores an integer as its value, then convert that string into an actual integer object using int() ; test that your new object is really a number by multiplying it by another number and displaying the result. ''' number = "12" real_number = int(number) print(real_number*3) ''' Review 2: Create a string object and an integer object, then display them side-by-side with a single print statement by using the str() function ''' string = "This is the number" integer = 2 print(string, integer)