text
stringlengths
37
1.41M
# 字符串处理 def handleString(): print('picnicItems'.center(20,'-')) # 输出以指定字符串为中心的长度为20的字符串 print('*'.ljust(15, '-') + 'Hello'.rjust(5)) print('Hello'.ljust(15) + '*'.rjust(5)) print(' \n\tHello'.strip()) print(' \n\tHello'.lstrip()) # 去除左边的空格、换行、制表符 print(' \n\tHello'.rstrip()) # 去除右边的空格、换行、制表符 print('Hello world'.strip('leh')) """ 输出像列表一样 """ def printTableLike(): picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000} print('picnicItems'.center(20,'-')) for k,v in picnicItems.items(): print(k.ljust(14,'.') + str(v).rjust(6)) # 获取数组中元素最大字符串长度 def getMaxLengthOfList(tempList): length = 0 for item in tempList: if len(item) > length: length = len(item) return length # 输出列表 def printTable(): tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] resultList = [''] * 4 for index in range(len(tableData)): tempList = tableData[index] tempLength = getMaxLengthOfList(tempList) for index1 in range(len(tempList)): resultList[index1] += tempList[index1].ljust(tempLength + 5) for item in resultList: print(item) #printTableLike() #handleString() printTable()
meal = { "entree": "salmon", "drink": "wine", "dessert": "cheesecake" } #print(meal["dessert"]): #print("tonight I will have %s for dinner, with %s for dessert." % (meal["entree"], meal["dessert"]) #print("tonight I will have " + meal["entree" +" for dinner, with dessert"])) #if "dessert" in meal: # print("Of COURSE Sean had dessert!!!") #else: # print("Sean did NOT have dessert, and now he is sad.") print(meal) meal["entree"] = "salmon" meal["drink"] ="wine" del meal["dessert"] print(meal)
from random import randint from pprint import pprint from random import shuffle def huuuh_sonny(): while True: response = input('You: ') if response == 'BYE': print('GRANDMA: BYE SONNY') break elif response.isupper(): print('Grandma: NO, NOT SINCE {}!'.format(randint(1930, 1950))) else: print( 'Grandma: HUUUH!!?....WHAT THE HECK YOU SAYIN,SPEAK UP...SONNY!!!' ) def grader(): grades = [] while True: grade = input('Your Grade: ').strip() if grade == 'quit': break else: grades.append(int(grade)) average = round(sum(grades) / len(grades)) print(average) if average >= 90: print('Your grade is: A') elif average >= 80: print('Your grade is: B') elif average >= 70: print('Your grade is: C') elif average >= 65: print('Your grade is: D') elif average <= 64: print('Your grade is: F, and you failed stupid!!!') def what_you_doin(): while True: name = input( '\nWhat is your name?(first,last name.): ').strip().lower() if name == 'nate clark': print('\nI am the Technical Director.') if name == 'sean anthony': print('\nI am the Director.') if name == 'kagan coughlin': print('\nI am a co-founder') if name == 'sage nichols': print('\nI am a Founding Trustee') if name == 'edgar guzman': print('\nI was in the graduated class 0f 2017') if name == 'daniel peterson': print('\nI am a current student, and is gonna be the best!!!!') if name == 'cody van der poel': print('\nI am a current student and I am from Charleston.') elif name == 'done': break def two_player_war(): from random import randint, shuffle deck = [ 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14 ] shuffle(deck) Daniels_hand = deck[:26] Rays_hand = deck[26:] Daniels_pile = [] Rays_pile = [] deck = [] treasure_cards = [] while True: if len(Daniels_hand) == 0: if len(Daniels_pile) == 0: print('Big Razzor wins!') break Daniels_hand.extend(Daniels_pile) Daniels_pile = [] daniels_card = Daniels_hand.pop() if len(Rays_hand) == 0: if len(Rays_pile) == 0: print('Dannyp wins!') break Rays_hand.extend(Rays_pile) Rays_pile = [] rays_card = Rays_hand.pop() deck.extend([daniels_card, rays_card]) print('\nDaniel: drew {} \nRay: drew {}'.format( daniels_card, rays_card)) shuffle(deck) input() if daniels_card > rays_card: print('\tThe Danny P wins!') Daniels_pile.append(daniels_card) Daniels_pile.append(rays_card) Daniels_pile.extend(treasure_cards) treasure_cards = [] elif rays_card > daniels_card: print('\tOne more for Raynard!') Rays_pile.append(rays_card) Rays_pile.append(daniels_card) Rays_pile.extend(treasure_cards) treasure_cards = [] else: treasure_cards.append(daniels_card) treasure_cards.append(rays_card) if len(Daniels_hand) == 0: if len(Daniels_pile) == 0: print('Big Razzor wins!') break Daniels_hand.extend(Daniels_pile) Daniels_pile = [] dp_cards = Daniels_hand.pop() treasure_cards.append(dp_cards) if len(Daniels_hand) == 0: if len(Daniels_pile) == 0: print('Big Razzor wins!') break Daniels_hand.extend(Daniels_pile) Daniels_pile = [] dp_cards = Daniels_hand.pop() treasure_cards.append(dp_cards) if len(Daniels_hand) == 0: if len(Daniels_pile) == 0: print('Big Razzor wins!') break Daniels_hand.extend(Daniels_pile) Daniels_pile = [] dp_cards = Daniels_hand.pop() treasure_cards.append(dp_cards) if len(Rays_hand) == 0: if len(Rays_pile) == 0: print('Dannyp wins!') break Rays_hand.extend(Rays_pile) Rays_pile = [] rt_cards = Rays_hand.pop() treasure_cards.append(rt_cards) if len(Rays_hand) == 0: if len(Rays_pile) == 0: print('Dannyp wins!') break Rays_hand.extend(Rays_pile) Rays_pile = [] rt_cards = Rays_hand.pop() treasure_cards.append(rt_cards) if len(Rays_hand) == 0: if len(Rays_pile) == 0: print('Dannyp wins!') break Rays_hand.extend(Rays_pile) Rays_pile = [] rt_cards = Rays_hand.pop() treasure_cards.append(rt_cards) def chores_assigner(): from random import randint, shuffle students = [ 'Cody Vander Poel:', 'Desma Hervey:', 'Daniel Peterson:', 'Tim Bowling:', 'Henry Moore:', 'Ray Turner:', 'Justice Taylor:', 'Ginger Keys:', 'Logan Harrell:', 'Irma Patton:', 'Cole Anderson:', 'Matt Lipsey:', 'John Morgan:', 'Andrew Wheeler:', 'Jakylan Standifer:', 'Myisha Madkins:' ] chores = [ 'Monday Lunch set-up/clean up', 'Tuesday Lunch set-up/clean up', 'Wednesday Lunch set-up/clean up', 'Thursday Lunch set-up/clean up', 'Friday Lunch set-up/clean up', 'Check trash and sweep classroom floor DAILY', 'Take kitchens trash out DAILY', 'Sweep stairs DAILY', 'Friday sweep hallways', 'Keep classroom organized DAILY', 'Restock water when needed', 'Friday clean bathroom 1', 'Friday clean bathroom 2', 'Take trash out of bathrooms', 'Take boxes to trash', 'Help others' ] shuffle(students) for student in students: print() print(student, chores.pop()) def card_score(card): if isinstance(card, int): return card elif card == 'J': card = 10 elif card == 'Q': card = 10 elif card == 'K': card = 10 elif card == 'A': card = 11 return card def hand_score(hand): ''' list -> int >>> hand_score([2, 3, 4]) 9 >>> hand_score(['K', 'Q']) 20 >>> hand_score(['A', 9]) 20 ''' total = 0 for card in hand: total = total + card_score(card) return total def black_jack(): deck = [ 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 'J', 'Q', 'K', 'A' ] new_deck = [] shuffle(deck) dealer_cards = [] player_cards = [] while True: print('\n-*-*-*-*-Welcome to Black Jack-*-*-*-*-') print() welcome = input('\tHit Enter to continue\n').strip() if welcome == 'Enter': continue else: break while len(dealer_cards) != 2: dealer_cards.append(deck.pop()) dealer_cards.append(deck.pop()) if len(dealer_cards) == 2: print('The Dealer has: __ , ', dealer_cards[1]) while len(player_cards) != 2: player_cards.append(deck.pop()) player_cards.append(deck.pop()) if len(player_cards) == 2: print('You Have: ', player_cards, hand_score(player_cards)) if hand_score(dealer_cards) == 21: print('The Dealer has reached 21 and wins the game!!') return elif hand_score(dealer_cards) > 21: print('The Dealer has busted and loses the game!!') while hand_score(player_cards) < 21: responce = input('Would you like to hit or stay??').strip().lower() while hand_score(dealer_cards) <= 18: dealer_cards.append(deck.pop()) if hand_score(dealer_cards) > 21: print('The dealer BUSTED... You win!!!') return if responce == 'hit': player_cards.append(deck.pop()) print('You now have a total of {} from these cards: {}'.format( str(hand_score(player_cards)), str(player_cards))) else: print('The dealer has a total of {} from these cards: {}'.format( str(hand_score(dealer_cards)), str(dealer_cards))) print('You have a total of {} from these cards {}'.format( str(hand_score(player_cards)), str(player_cards))) break if hand_score(player_cards) == hand_score(dealer_cards): print('Its a tie....The dealer Wins!!!') elif hand_score(player_cards) > 21: print('You BUSTED....The dealer wins!!!') elif hand_score(player_cards) < hand_score(dealer_cards): print('The dealer Wins!!!') elif hand_score(player_cards) > hand_score(dealer_cards): print('You Win!!!') elif hand_score(player_cards) == 21: print('You have 21!!....You won Black Jack!!') elif hand_score(dealer_cards) == 21: print('The Dealer has 21.... The dealer won Black Jack!!') def hey_you(): name = input('What is your name??') print('Whats up, ' + name) def main(): while True: black_jack() input( '\n Would you like to play again???\n\tHit Enter to play again.' ) # hey_you() # what_you_doin() # grader() # huuuh_sonny() # two_player_war() # chores_assigner() if __name__ == '__main__': main()
''' 题目: 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。 ''' ''' 思路: 大致分为两种节点:有右子节点的,无右子节点的。 有右子节点的,根据中序遍历的顺序,它一定是某子树的根节点,所以下一节点就是其右子节点的最左子节点; 无右子节点的,先考虑是其父节点的左子节点还是右子节点。 若是其父节点的左子节点,那么下一节点就是其父节点。 若是其父节点的右子节点,情况较复杂。。。 复杂情况的节点:如果一个节点既没有右子树,并且它还是它父节点的右子节点。 可以沿着它的父节点一直向上遍历,直到找到一个节点——是其父节点的左子节点,如果这样的情况存在,那么该节点的父节点就是下一节点。 ''' # 注意:“树中的节点同时包含了指向父节点的指针”——Node.next -> Node.parernt class Solution: def GetNext1(self, pNode): if not pNode: return #先考虑有右子节点的 if pNode.right != None: pNode = pNode.right while pNode.left != None: pNode = pNode.left return pNode #再考虑无右子节点的 elif pNode.next != None: #有父节点的, while pNode.next != None and pNode == pNode.next.right: #这句前后顺序不可倒 pNode = pNode.next pNode = pNode.next return pNode else: return pNode.next # 更好的实现版本 def GetNext2(self, pNode): # write code here if pNode is None: return # 注意当前节点是根节点的情况。所以在最开始设定pNext = None, 如果下列情况都不满足, 说明当前结点为根节点, 直接输出None pNext = None #有右子节点的情况: if pNode.right: pNode = pNode.right while pNode.left: pNode = pNode.left pNext = pNode #无右子节点的情况: else: if pNode.next and pNode.next.left == pNode: pNext = pNode.next elif pNode.next and pNode.next.right == pNode: pNode = pNode.next while pNode.next and pNode.next.right == pNode: pNode = pNode.next #终止时, 1:当前节点有父节点,说明当前节点是父节点的左子节点 # 2: 当前节点无父节点(根节点),说明当前节点在位于根节点的右子树,所以没有下一个节点 if pNode.next: pNext = pNode.next return pNext
''' 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。 ''' # -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # write code here meetingNode = self.MeetingNode(pHead) if not meetingNode: return None # 得到环中节点的数目 nodesInLoop = 1 FlagNode = meetingNode while FlagNode.next != meetingNode: FlagNode = FlagNode.next nodesInLoop += 1 # 先移动pNode1,先走环中节点的数目 pNode1 = pHead for i in range(nodesInLoop): pNode1 = pNode1.next pNode2 = pHead while pNode1 != pNode2: pNode1 = pNode1.next pNode2 = pNode2.next return pNode1 def MeetingNode(self, pHead): if not pHead: return None pSlow = pHead.next if not pSlow: return None pFast = pSlow.next while pFast and pSlow: if pFast is pSlow: return pFast pSlow = pSlow.next # 漫指针每次走一步 pFast = pFast.next # 快指针每次走两步 if pFast: pFast = pFast.next return None node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node6 = ListNode(6) node7 = ListNode(7) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node5.next = node6 node6.next = node7 node7.next = node4 s = Solution() print(s.EntryNodeOfLoop(node1).val) #设计的环入口是节点4,其值返回也应该是4.
''' 题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。 ''' ''' 思路1: 哈希表,从头到尾扫描,每扫描到一个数字,都可以用O(1)的时间来判断哈希表里是否已经包含这个数字。 如果已经包含,就找到一个重复的数字。时间复杂度O(n), 空间复杂度O(n)。 ''' class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, numbers, duplication): if not numbers: return False nums = [] #用一个数组做哈希表 for i in numbers: if i in nums: duplication[0] = i return True nums.append(i) return False ''' 思路2: 因为数组中的数字都是0~n-1的范围内,如果其中没有重复数字的话,那么排序后数字i将出现在下标为i的位置。 重排数组,从头到尾扫描,当扫描到下标i的数字时,首先比较该数字(m)是否等于i。若是,继续扫描下一个;若不是,则拿它和下标为m的数字作比较。 如果它和第m个数字相等,就找到一个重复数字;如果不相等,就把第i个和第m个数字交换, 把数字m放到属于它的位置上。 时间复杂度是O(n), 空间复杂度是O(1) ''' class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, numbers, duplication): if not numbers: return False length = len(numbers) for i in range(length): while numbers[i] != i: temp = numbers[i] if numbers[i] == numbers[temp]: duplication[0] = numbers[i] return True numbers[i] = numbers[temp] numbers[temp] = temp; return False
''' 题目: 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。 ''' ''' 思路: 大致分为两种节点:有右子节点的,无右子节点的。 有右子节点的,根据中序遍历的顺序,它一定是某子树的根节点,所以下一节点就是其右子节点的最左子节点; 无右子节点的,先考虑是其父节点的左子节点还是右子节点。 若是其父节点的左子节点,那么下一节点就是其父节点。 若是其父节点的右子节点,情况较复杂。。。 复杂情况的节点:如果一个节点既没有右子树,并且它还是它父节点的右子节点。 可以沿着它的父节点一直向上遍历,直到找到一个节点——是其父节点的左子节点,如果这样的情况存在,那么该节点的父节点就是下一节点。 ''' # 注意:“树中的节点同时包含了指向父节点的指针”——Node.next -> Node.parernt class Solution: def GetNext(self, pNode): if not pNode: return #先考虑有右子节点的 if pNode.right != None: pNode = pNode.right while pNode.left != None: pNode = pNode.left return pNode #再考虑无右子节点的 elif pNode.next != None: #有父节点的, while pNode.next != None and pNode == pNode.next.right: #这句前后顺序不可倒 pNode = pNode.next pNode = pNode.next return pNode else: return pNode.next
# VARIABLE DECLARATION something = 10 # IF, ELSIF AND ELSE if something == 10: print ("Something is : ", something) elif something == 11: print ("Something is 11") else: print ("Something has some other value!") # LIST num = [1,2,3,4,5,6] print (min(num)) print (max(num)) print (sum(num)) num_vowels = 0 string = "My name is abhshek" # FUNCTIONS def is_vowel(c): if c in 'aeiouAEIOU': return True return False # FOR LOOP for char in string: if is_vowel(char): num_vowels = num_vowels + 1 print ("Total vowels : ", num_vowels) # DICTIONARY dict = { "NAME" : "ABHISHEK KUMAR RAI", "COLLEGE" : "UVCE" } print (dict.get("NAME")) print (dict.get("COLLEGE")) dict["NAME"] = "ASDFASDF" print (dict.get("NAME")) print (dict.get("COLLEGE")) # SET IN PYTHON. DUPLICATE ELEMENTS NOT THERE. set_var = set() for i in range (1, 11): set_var.add(i) print (set_var)
import random import statistics def randit(): tab = [] for i in range(0 , 250): tab.append(random.randint(0,300)) return tab def mediana(a): b = 0 for x in a: b += x return b/len(a) def sortuj(a): a.sort() a.reverse() return a def check(a): tab = [] for x in range(0,len(a)-1): for y in range(0 , len(a)-1): if ((x != y) and a[x] == a[y] ) : # print("sdsdsdds") tab.append(a[x]) tab.sort() tab.reverse() tab = set(tab) tab = sorted(tab) return tab #def mediana(a): # if len(a) % 2 != 0: # return a[(len(a)-1)/2] # else: # return (a[len(a)/2]+a[(len(a)/2)-1])/2 def check_if_no(a): bb = check(a) tab = list(range(0,300)) p = 0 for i in tab: for x in bb: if i == x: tab.remove(i) return tab if __name__ == '__main__': print(randit()) print(mediana(randit())) print(sortuj(randit())) print(statistics.median(randit())) print(statistics.stdev(randit())) print(check(randit())) xd = randit() xd.sort() print(xd) print(check(xd)) print(check_if_no(xd))
#!encoding=utf-8 import math #调用函数 print abs(100) print abs(-20) print abs(12.34) print cmp(1,2) print cmp(2,1) print cmp (3,3) print int('123') print int(12.34) print float('12.34') print str(1.23) print unicode(100) print bool(1) print bool('') a=abs print a(-2) #定义函数 def my_abs(x): if x>=0: return x if x<0: return -x print my_abs(-9) ''' 如果想定义一个什么事也不做的空函数,可以用pass语句: def nop(): pass pass语句什么都不做,那有什么用?实际上pass可以用来作为占位符,比如现在还没想好怎么写函数的代码,就可以先放一个pass,让代码能运行起来。 if age >= 18: pass ''' age=15 if age>=18: pass ''' 当传入了不恰当的参数时,内置函数abs会检查出参数错误,而我们定义的my_abs没有参数检查,所以,这个函数定义不够完善。 让我们修改一下my_abs的定义,对参数类型做检查,只允许整数和浮点数类型的参数。数据类型检查可以用内置函数isinstance实现: ''' print my_abs('A') def my_abs_new(x): if not isinstance(x,(int,float)): raise TypeError('bad type') if x>=0: return x if x<0: return -x #print my_abs_new('A') 参数类型错误 #返回多个值 def move(x,y,step,angle=0): nx = x + step * math.cos(angle) ny = y + step * math.sin(angle) return nx,ny x,y = move(10,10,10,math.pi/6) #其实是返回了一个tuple r=move(10,10,10,math.pi/6) print x,y print r #默认参数 def power(x): return x*x print power(5) #x^n def power(x,n=2): s=1 while(n>0): s=s*x n=n-1 return s print power(5,3) print power(5) def enroll(name,gender,age=6,city='Beijing'): print 'name', name print 'gender', gender print 'age',age print 'city',city print enroll('zhoud',9) print enroll('zhoud',9,city='anhui') #定义可变参数和定义list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数numbers接收到的是一个tuple, #因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数: def calc(number): sum=0 for x in number: sum=sum+x return sum print calc([1,2,3,4,5]) def calc_new(*number): sum=0 for x in number: sum=sum+x return sum print calc_new(1,2,3,4,5,6) nums=[1,2,3] print calc_new(*nums) #关键字参数传入dict def person(name,age,**kw): print name,age,kw person('zhoud',23) person('zhoud',23,gender='M',job='Engineer') ''' 在Python中定义函数,可以用必选参数、默认参数、可变参数和关键字参数,这4种参数都可以一起使用, 或者只用其中某些,但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数和关键字参数。 ''' def func(a,b,c=0,*d,**kw): print 'a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw func(1,2) func(1,2,3) func(1,2,3,4,5) #amazing a=(1,2,3,4) b={'x':99} func(*a,**b) #递归函数 def fact(n): if n==1: return 1 else: return n*fact(n-1) print fact(5)
#!encoding=utf-8 #python中{}表示字典dict []表示列表list ()表示元组tuple 所指向的内容不可更改 d={'Michael':95,'Bob':75,'Tracy':85} print d['Michael'] print d.get('Michael',-1) print d.get('Tom',-1) print d d.pop('Bob') print d ''' set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。 要创建一个set,需要提供一个list作为输入集合: ''' s=set([1,2,3]) print s #重复元素回被删除 m=set([1,1,2,2,3,3]) print m m.add(4) print m m.remove(4) print m #set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作: s1=set([1,2,3]) s2=set([2,3,4]) print s1&s2 print s1|s2 x=(1,2,3) m.add(x) print m
#! /usr/bin/env python # -*- encoding=utf-8 -*- a=[6,4,8,9,3] #sorted 返回列表不改变自身,sort无返回值,改变自身 print sorted(a) print a print a.sort() print a strs=['aa','bb','zz','CC'] print sorted(strs) print sorted(strs,reverse=True) strs1=['aaaa','aaa','a','aa'] print sorted(strs1,key=len) print sorted(strs,key=str.lower) strs2=['bd','jn','ci','wo'] def fu1(s): return s[-1] print sorted(strs2,key=fu1) print sorted(strs2,key=(lambda x: x[-1])) nums=[1,2,3,4] squares=[a*a for a in nums] print squares #upper()大写,lower()小写 str3=['HEllo','world','nihao'] str4=[x.lower()+'!!!' for x in str3] print str4
# -*- coding: utf-8 -*- ''' autor: Jose Jasnau Caeiro data: 12 de marco de 2012 obs.: realizacoes das funcoes de calculo dos numeros de fibonacci ''' def fibonacci_recursivo(n): ''' realizacao recursiva do calculo dos numeros de fibonacci n - argumento inteiro positivo ''' if n == 0: return 0 elif n == 1: return 1 else: return fibonacci_recursivo(n-2) +\ fibonacci_recursivo(n-1) def fibonacci_iterativo(n): ''' realizacao iterativa ''' i = 1 j = 0 for k in range(n): t = i + j i, j = j, t pass return j
#!/usr/bin/python3 import sys for line in sys.stdin: words = line.strip().split() print(" ".join([word.capitalize() for word in words]))
yes_no = "" motor_val = "" b ={ 'a' : 122, 'b' : 123, 'l' : "left", 'r' : "right" } # get user input while yes_no != "n": inp = raw_input('input a character : ') if inp == "n": break print'The result is: ' print(b.get(inp, -1)) print 'Exiting loop'
#!/usr/bin/env python # -*- coding: utf-8 -*- # To understand special characters import socket # For compatibility with python 2 and 3 try: input = raw_input except NameError: pass ip_server = input("Dirección del servidor: ") server_port = 5000 message = " " str_response = " " stop_printing = ["continue", "end", "endGame"] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def continous_printing(): global str_response while str_response not in stop_printing: print(str_response) response = s.recv(1024) str_response = response.decode('utf-8') name = input("Nombre de jugador: ") s.sendto(name.encode('utf-8'), (ip_server, server_port)) print(s.recv(1024).decode('utf-8')) while message != "quit" and str_response != "endGame": while str_response != "Your turn" and str_response != "Ending game...": response = s.recv(1024) str_response = response.decode('utf-8') print(str_response) if str_response == "Ending game...": break response = s.recv(1024) str_response = response.decode('utf-8') continous_printing() while message != "endTurn": message = input("Query: ") s.sendto(message.encode('utf-8'), (ip_server, server_port)) response = s.recv(1024) str_response = response.decode('utf-8') continous_printing() if str_response == "end" or str_response == "endGame": break message = " " response = s.recv(1024) str_response = response.decode('utf-8') print(str_response) s.close()
# Enter your code here. Read input from STDIN. Print output to STDOUT n = float(raw_input()) numbers = map(int, raw_input().split(' ')) positives = 0 zeros = 0 for num in numbers: if num > 0: positives += 1 elif num == 0: zeros += 1 print positives/n print (n-positives-zeros)/n print zeros/n
import re n = int(input()) pattern = r'[a-z]{,3}\d{2,8}[A-Z]{3,}' regex = re.compile(pattern) for _ in range(0, n): s = input() if (regex.match(s)): print('VALID') else: print('INVALID')
# Enter your code here. Read input from STDIN. Print output to STDOUT raw_input() print reduce(lambda x, y: x+y, map(int, raw_input().split()))
import re regex = r"(.*?)hackerrank(.*)" rows = int(input()) for i in range(0, rows): s = input() match = re.match(regex, s) if (match): g1 = len(match.group(1)) g2 = len(match.group(2)) if (g1 > 0 and g2 > 0): print(-1) elif (g2 > 0): print(1) elif (g1 > 0): print(2) else: print(0)
#!/bin/python3 import sys def separateNumbers(s): for first_number_length in range(1, 1+len(s)//2): n = int(s[:first_number_length]) remainder = s[first_number_length:] expected = n+1 while len(remainder) > 0: if remainder.startswith(str(expected)): remainder = remainder[len(str(expected)):] expected += 1 else: break if len(remainder) == 0: print("YES " + str(n)) return print("NO") if __name__ == "__main__": q = int(input().strip()) for a0 in range(q): s = input().strip() separateNumbers(s)
# Enter your code here. Read input from STDIN. Print output to STDOUT n = int(raw_input()) fibonacci = [] for i in xrange(n): if i == 0: fibonacci.append(0) elif i <= 2: fibonacci.append(1) else: fibonacci.append(fibonacci[-2] + fibonacci[-1]) print map(lambda x: x**3, fibonacci)
#Desenvolva um programa que leia 6 números inteiros e mostre a soma apenas entre aqueles que forem pares, se o resultado da soma for ímpar desconsidere-o. soma = 0 for c in range (1, 7): num = int(input(f'Digite o {c}º número: ')) if num % 2 == 0: soma += num if soma % 2 == 0: print(f'A soma entre os números pares é {soma}') elif soma < 2 or soma % 2 != 0: print('O resultado da soma é ímpar.')
#Faça um programa que leia um número qualquer e mostre seu fatorial. #from math import factorial num = int(input('Informe um número: ')) c = num res = 1 print(f'Calculando {num}! = ', end='') while c > 0: print(f'{c}', end='') print(' x ' if c > 1 else ' = ', end='') res *= c c -= 1 print(res)
#'''Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final de acordo com a média atingida. # Média abaixo de 5.0 = REPROVADO # Média entre 5.0 e 6.9 = RECUPERAÇÃO # Media 7.0 ou superior = APROVADO''' nota1 = float(input('Primeira nota: ')) nota2 = float(input('Segunda nota: ')) media = (nota1 + nota2) / 2 if media < 5.0: print(f'Sua média foi de {media} \nREPROVADO!') elif media <= 6.9: print(f'Sua média foi de {media} \nRECUPERAÇÂO!') elif media >= 7.0: print(f'Sua média foi de {media} \nAPROVADO!')
#Refaça o exercício 51, lendo o primeiro termo e a razão de um PA mostrando os 10 primeiros termos da progressão usando a estrutura while. print('Progressão aritimética') print('=-='*10) termo = int(input('Primeiro termo: ')) razao = int(input('Razão da PA: ')) c = 1 while c <= 10: print(f'{termo} ', end='') print('- ' if c < 10 else '', end='') termo += razao c += 1
#Crie um programa que leia vários valores inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles. numero = int(input('Informe um número [999 para parar]: ')) quantidade = 0 soma = 0 while numero != 999: quantidade += 1 soma += numero numero = int(input('Informe um número [999 para parar]: ')) print(f'Foram digitados {quantidade} números e a soma entre eles é: {soma}')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Created on Mon Sep 25 22:55:27 2017 __author__ = "nihat kocyigit" __license__ = "GPL" __version__ = "1.0.0" __email__ = "nihatkoc@gmail.com" __status__ = "Production" #============================================================================== # english # In many practical Data Science activities, the data set will contain # categorical variables. These variables are typically stored as text values # which represent various traits. Some examples include color # (“Red”, “Yellow”, “Blue”), size (“Small”, “Medium”, “Large”) or # geographic designations (State or Country). Regardless of what the value # is used for, the challenge is determining how to use this data in the # analysis. Many machine learning algorithms can support categorical values # without further manipulation but there are many more algorithms that do not. # Therefore, the analyst is faced with the challenge of figuring out how to # turn these text attributes into numerical values for further processing. # Label encoding has the advantage that it is straightforward but it has the # disadvantage that the numeric values can be “misinterpreted” by the # algorithms. For example, the value of 0 is obviously less than the value # of 4 but does that really correspond to the data set in real life? # A common alternative approach is called one hot encoding. # Despite the different names, the basic # strategy is to convert each category value into a new column and assigns # a 1 or 0 (True/False) value to the column. This has the benefit of not # weighting a value improperly but does have the downside of adding more # columns to the data set. # code uses the function from sklearn #============================================================================== #============================================================================== # turkish # Bircok pratik Data Science aktivitesinde, veri setinde kategorik degiskenler # yer alacaktir. Bu degişkenler genellikle cesitli ozellikleri temsil eden # metin degerleri olarak saklanir. Bazı ornekler arasinda renk # ("Kirmizi", "Sari", "Mavi"), boyut ("Kucuk", "Orta", "Buyuk") veya cografi # belirtimler (Eyalet veya Ulke) bulunur. Degerin ne icin kullanildigina # bakilmaksizin, analizde bu verilerin nasil kullanilacagini belirlemek # zordur. Pek cok makine ögrenme algoritmasi, kategorik degerleri baska # manipulasyon olmadan destekleyebilir, ancak bunu yapmayan daha bircok # algoritma vardir. Bu nedenle, analist, bu metin niteliklerini sonraki # isleme icin sayisal degerlere donusturme problemi ile karsi karsiya kalir. # Label encoding basit olmasi avantajlidir, ancak sayisal degerlerin # algoritmalar tarafindan "yanlis yorumlanmasi" gibi dezavantaja sahiptir. # Ornegin, 0 degeri aciktir ki 4 degerinden kucuktur, ancak bu gercek # yasamdaki veri kumesine karsilik gelmekte midir? # Ortak bir alternatif yaklasim, OneHotEncoding olarak adlandirilir # Farkli adlara ragmen, temel strateji her kategori degerini yeni bir sutuna # donusturmek ve sutuna 1 veya 0 (Dogru / Yanlis) degeri atamaktir. Bu, bir # degerin yanlis bir sekilde agirliklandirilmama avantajina sahiptir; ancak, # veri kumesine daha fazla sutun ekleme dezavantajina sahiptir. # sklearn kutuphanesinden ilgili fonksiyon kullanilmaktadir #============================================================================== # importing the libraries import pandas as pd import os # find the path to the dataset looking_for = 'ann-deep-learning' current_path = os.path.dirname(os.path.realpath('__file__')) index = current_path.find(looking_for) root_path = current_path[:index + len(looking_for)] # importing the dataset, specifying the seperator as ";" dataset = pd.read_csv(root_path+'/datasets/cars.csv', sep=';') print(dataset.shape) # print the dataset column names columns = dataset.columns print(columns) # columns for the one hot encoding using the pandas get_dummies method # this will add the fields 'Origin_CAT', 'Origin_Europe', 'Origin_Japan', # 'Origin_US' cols_to_transform = [ 'Origin' ] dataset_with_dummies = pd.get_dummies(dataset, columns = cols_to_transform ) # let's print the new dataset with the dummy fields # 'Origin_CAT', 'Origin_Europe', 'Origin_Japan','Origin_US' columns = dataset_with_dummies.columns print(columns)
# -*- coding: utf-8 -*- """ @author: Michal Problem A common substring of a collection of strings is a substring of every member of the collection. We say that a common substring is a longest common substring if there does not exist a longer common substring. For example, "CG" is a common substring of "ACGTACGT" and "AACCGGTATA", but it is not as long as possible; in this case, "GTA" is a longest common substring of "ACGTACGT" and "AACCGTATA". Note that the longest common substring is not necessarily unique; for a simple example, "AA" and "CC" are both longest common substrings of "AACC" and "CCAA". Given: A collection of k (k≤100) DNA strings of length at most 1 kbp each in FASTA format. Return: A longest common substring of the collection. (If multiple solutions exist, you may return any single solution.) """ from functools import wraps def memo(func): cache = {} @wraps(func) def wrap(*args): if args not in cache: cache[args] = func(*args) return cache[args] return wrap def lcp(i, j, s): ret = 0 n = len(s) for k in range(n): if i+k >= n or j+k >=n: break if s[i+k] != s[j+k]: break ret += 1 return ret #print lcp(1, 3, "banana$") def suffix_lcp(s): n = len(s) ss = [i for i in range(n)] suffix = sorted(ss, key = lambda x: s[x:]) lcp_arr = [lcp(suffix[i - 1], suffix[i], s) for i in range(1, n)] return suffix, lcp_arr class Node(object): def __init__(self, next_node_num, p_edge, parent): self.is_root = False self.active_length = 0 self.node_num = next_node_num self.p_edge = p_edge self.parent = parent self.lps_node = None self.first_info_node_in_subtree = None self.last_info_node_in_subtree = None first_info_node, last_info_node = None, None self.edges = {} def get_p_edge_len(self): if self.is_root: return 0 return self.p_edge[1] - self.p_edge[0] def compute_active_length(self): if self.is_root: return self.active_length = self.parent.active_length + self.get_p_edge_len() def edges_to_string(self): ret = "" for edge, child_node in self.edges.items(): ret = ret + "[" + str(edge) + ":" + str(child_node.node_num) + "]," return ret def edges_to_string_full(self, text): ret = "" for edge, child_node in self.edges.items(): ret = ret + "[" + text[edge[0]:edge[1]] + ":" + str(child_node.node_num) + "]," return ret def node_num_to_alphabet(self): A_ord = ord('A') return chr(self.node_num + A_ord) class SuffixTree(object): maxInd = 2**30 end_symbol = "#" s_separator = "$" def __init__(self, text): self.text = text + SuffixTree.end_symbol self.info_nodes=[] self.n = len(self.text) self.next_node_num = 0 self.root = self.build_node(None, None) self.root.is_root = True self.build_suffix_tree() def build_node(self, p_edge, parent): new_node = Node(self.next_node_num, p_edge, parent) self.next_node_num += 1 return new_node def get_edge_text(self, edge): #if self.n == edge[1]: # return str(edge[0]) + "+" return self.text[edge[0]: edge[1]] def generate_first_last_info_nodes(self): def generate_first_last_info_nodes_subtree(node): if not node.edges: node.first_info_node_in_subtree = node.node_num node.last_info_node_in_subtree = node.node_num else: minval, maxval = 0, SuffixTree.maxInd for child in node.edges.values(): child_minval, child_maxval = generate_first_last_info_nodes_subtree(child) minval, maxval = min(minval, child_minval), max(child_maxval, maxval) node.first_info_node_in_subtree = minval node.last_info_node_in_subtree = maxval return node.first_info_node_in_subtree, node.last_info_node_in_subtree generate_first_last_info_nodes_subtree(self.root) def build_suffix_tree(self): # lbi(i,i) >= i + active_length + min_dist lbi, min_dist = 0, 0 active_node, active_length = self.root, 0 last_created_branch_node = None for phase_i in range(self.n): print "#####phase:{phase}#####".format(phase=str(phase_i)) self.print_tree() if active_node.lps_node is not None: # follow suffix pointer active_node = active_node.lps_node active_length = max(active_length - 1, 0) else: active_node = self.root active_length = 0 min_dist = max(0, lbi - phase_i - active_length) print "active_node={0}, activeL={1}, minDist={2}".format(active_node.node_num_to_alphabet(), active_length, min_dist) walk_ret = self.walk_down_tree(active_node, active_length, min_dist, (phase_i, self.n)) active_node, active_edge , split_point, success, lbi = walk_ret print active_node.node_num, active_edge, split_point, success, lbi active_length = active_node.active_length if success: # completely matched pattern. Suffix is already in the tree! continue if active_edge is None: #create new information edge from active node new_node = self.build_node((lbi, self.n), active_node ) active_node.edges[(lbi, self.n)] = new_node self.info_nodes.append(new_node.node_num) if last_created_branch_node is not None: last_created_branch_node.lps_node = active_node last_created_branch_node = None else: # mismatch, we found splitting point #create new branch Node split_edge_head =(active_edge[0], active_edge[0] + split_point) new_branch_node = self.build_node( split_edge_head, active_node ) #fix previous child described by active_node and active_edge old_child = active_node.edges.pop(active_edge) split_edge_rest =(active_edge[0] + split_point, old_child.p_edge[1]) active_node.edges[split_edge_head] = new_branch_node new_branch_node.edges[split_edge_rest] = old_child old_child.p_edge = split_edge_rest old_child.parent = new_branch_node # create new Information Node new_info_node = self.build_node((lbi, self.n), new_branch_node ) self.info_nodes.append(new_info_node.node_num) new_branch_node.edges[(lbi, self.n)] = new_info_node new_branch_node.compute_active_length() if last_created_branch_node is not None: last_created_branch_node.lps_node = new_branch_node if active_node.is_root and new_branch_node.get_p_edge_len() == 1: #this branch node suffix pointer need to be pointed to root new_branch_node.lps_node = self.root last_created_branch_node = None else: last_created_branch_node = new_branch_node print "--------Building suffix tree finished-------" return def print_tree(self): def print_node(node, level): #print "{indent} {node_id}:{edges}".format(indent="\t"*level, node_id= node.node_num, edges=node.edges_to_string_full(self.text)) #if not node.edges: return #print "{indent} [{p_edge}]->({node_id}):".format(indent=" "*level , # p_edge = self.get_edge_text(node.p_edge) if node.p_edge is not None else "", # node_id= node.node_num) A_ord = ord('A') print "{indent}{p_edge}(id={node_id}, lps={lps})".format(indent=" "*level, p_edge = self.get_edge_text(node.p_edge) + "---" if node.p_edge is not None else "", node_id= chr(node.node_num + A_ord), lps= chr(node.lps_node.node_num + A_ord) if node.lps_node is not None else "None") for edge, child_node in node.edges.items(): print_node(child_node, level + 1) print_node(self.root, 0) def walk_down_tree(self, node, active_length, min_distance, pattern_ind, pattern=None): """ active_node - Node from which to start walkdown pattern_ind - (start, end) indexes of pattern pattern - string with characters to compare Walk down tree, starting from node. Compare characters on edge with characters in pattern On mismatch return branchNode or edge and index with mismatch """ if pattern is None: pattern = self.text pattern_low, pattern_high = pattern_ind pattern_len = pattern_high - pattern_low pattern_i = active_length skip_n = min_distance active_node = node active_edge = None text = self.text split_point = 0 for edge, child_node in active_node.edges.items(): if text[edge[0]] == pattern[pattern_low + pattern_i]: active_edge = (edge, child_node) break if active_edge is None: # active_node is Information Node or there is no outgoing matching edge return active_node, active_edge , split_point, False, pattern_low + pattern_i for i in range(active_edge[0][0], active_edge[0][1]): if skip_n > 0: skip_n -= 1 pattern_i += 1 continue split_point = i - active_edge[0][0] if pattern_i >= pattern_len: # pattern ended, match is successfull return active_node, active_edge[0] , split_point, True, pattern_low + pattern_i if text[i] != pattern[pattern_low + pattern_i]: # mismatch, we found splitting point return active_node, active_edge[0] , split_point, False, pattern_low + pattern_i pattern_i += 1 # in this part we passed edge so we are in branchNode active_edge_length = active_edge[0][1] - active_edge[0][0] active_node = active_edge[1] return self.walk_down_tree(active_node, active_length + active_edge_length, skip_n, pattern_ind, pattern) #ss = SuffixTree("abab") #ss = SuffixTree("ababbabbaabbabb") #ss = SuffixTree("cdddcdc") ss = SuffixTree("abcabxabcd") ss.print_tree() #print suffix_lcp("banana$")
""" Example of pin implementation. This example only shows how to create a simple pinoccio model from a URDF file and then it compute the forward kinermatics REMARK: In this section we use the data model. the data model is a pinocchio class that stores relevant information about the kinematics and dynamics of the model. This class is used as an argument for much of the pinocchio functions in order used it and store its result """ from pathlib import Path # Loads URDF model into pinocchio from pinocchio import buildModelFromUrdf # Stores the forward kinematics of the joints into the data argument from pinocchio import rnea from pinocchio import computeRNEADerivatives from pinocchio import randomConfiguration import numpy as np def main(): ''' Main procedure 1 ) Build the model from an URDF file 2 ) compute forwardKinematics 3 ) compute forwardKinematics of the frames 4 ) explore data ''' model_file = Path(__file__).absolute( ).parents[1].joinpath('urdf', 'twolinks.urdf') model = buildModelFromUrdf(str(model_file)) # Create data required by the algorithms data = model.createData() # Sample a random configuration numpy_vector_joint_pos = randomConfiguration(model) numpy_vector_joint_vel = np.random.rand(model.njoints-1) numpy_vector_joint_acc = np.random.rand(model.njoints-1) # Calls Reverese Newton-Euler algorithm numpy_vector_joint_torques = rnea(model, data, numpy_vector_joint_pos, numpy_vector_joint_vel, numpy_vector_joint_acc) computeRNEADerivatives(model, data, numpy_vector_joint_pos, numpy_vector_joint_vel, numpy_vector_joint_acc) dtorques_dq = data.dtau_dq dtorques_dqd = data.dtau_dv dtorques_dqdd = data.M if __name__ == '__main__': main()
# Python Code Challenges: Control Flow (Advanced) # 1. IN RANGE # To test if a number falls within a certain range. Accept three parameters where the first parameter is the number being tested, the second parameter is the lower bound and the third parameter is the upper bound of the range. # Define the function to accept three numbers as parameters # Test if the number is greater than or equal to the lower bound and less than or equal to the upper bound # If this is true, return True, otherwise, return False def in_range(num, lower, upper): if(num >= lower and num <= upper): return True return False # test in_range function: print(in_range(10, 9, 11)) # should print True print(in_range(9, 10, 11)) # should print False # 2. SAME NAME # To check different names and determine if they are equal. Accept two strings and compare them. # Define the function to accept two strings, your_name and my_name # Test if the two strings are equal # Return True if they are equal, otherwise return False def same_name(your_name, my_name): if (your_name == my_name): return True else: return False # test same_name function: print(same_name("Sapphire", "Sapphire")) # should print True print(same_name("Sapphire", "Steel")) # should print False # 3. ALWAYS FALSE (Avoid creating conditions like this) # An if statement that is always false is called a contradiction. A contradiction occurs when the condition will always be false no matter what value is passed into it. # Define the function to accept a single parameter called num # Use a combination of <, > and and to create a contradiction in an if statement. # If the condition is true, return True, otherwise return False. def always_false(num): if (num > 0 and num < 0): return True else: return False # test always_false function: print(always_false(0)) # should print False print(always_false(-1)) # should print False print(always_false(1)) # should print False # 4. MOVIE REVIEW # Function that will help rate movies. The function will split the ratings into different ranges and tell the user how the movie was based on the movie’s rating. # Define function to accept a single number called rating # If the rating is equal to or less than 5, return "Avoid!" # If the rating was less than 9, return "Excellent!" # If neither of the if statement conditions were met, return "Don't Miss!" def movie_review(rating): if(rating <= 5): return "Avoid!" if(rating < 9): return "Excellent!" return "Don't miss!!" # test movie_review function: print(movie_review(10)) # should print "Don't miss!" print(movie_review(3)) # should print "Avoid!" print(movie_review(7)) # should print "Excellent!" # 5. MAX NUMBER # Select which number from three input values is the greatest using conditional statements. Check the different combinations of values to see which number is greater than the other two. # Define a function that has three input parameters, num1, num2, and num3 # Test if num1 is greater than the other two numbers # If so, return num1 # Test if num2 is greater than the other two numbers # If so, return num2 # Test if num3 is greater than the other two numbers # If so, return num3 # If there was a tie between the two largest numbers, then return "It's a tie!" def max_num(num1, num2, num3): if num1 > num2 and num1 > num3: return num1 elif num2 > num1 and num2 > num3: return num2 elif num3 > num1 and num3 > num2: return num3 else: return "It's a tie!" # test max_num function: print(max_num(-10, 0, 20)) # should print 20 print(max_num(-10, 1, -20)) # should print 1 print(max_num(-1, -10, -10)) # should print -1 print(max_num(1, 10, 10)) # should print "It's a tie!"
import random d = 0 p = 0 snl={8:37,13:34,38:9,11:2,28:4,40:68,52:81,76:97,65:46,93:64,89:70} def rolldice(): return random.randint(1,6) while True: r = input("press r to roll, q to quit : ") if r == 'r': d = rolldice() print("you got: ",d) if d == 6: print("congratulations!!,you can play now.") break else: print("roll again, till you get 6.") elif r == 'q': exit() while True: r = input("press r to roll, q to quit: ") if r == 'r': d = rolldice() print("you got : ",d) p = p+d if p > 100: p = p-d print("wait till you get", 100-p) print("your new position is: ",p) if p in snl: if p < snl[p]: print("wow, you got a lader ") else: print("oops,you got swallowed by a snake.") p = snl[p] print("move to ",p) if p == 100: print("you won!!!") exit() elif r == 'q': print("bye!") exit()
"""Tower of hanoi""" def tower_of_hanoi(n, initial, final, aux): """process of """ if n == 1: print("Move disk 1 from source", initial, 'to destination', final) return tower_of_hanoi(n-1, initial, aux, final) print('Move disk ', n, 'move from soutce', initial, 'to destination ', final) tower_of_hanoi(n-1, aux, final, initial) # user input while True: val = input('Enter the no of words: \n') try: n = int(val) break except ValueError: print('Enter the integer value.') # function call tower_of_hanoi(n, 'A', 'B', 'C')
#!/usr/bin/env python """ Utilites for displaying bitmaps on the display. """ import os from PIL import Image, ImageDraw, ImageFont def pil_to_lol(im, display_height, center = True): """ A generator which takes a PIL image and produces lines of pixel values suitable for the LineOfLife interface. Truncates images too tall for the display. Optionally centers images which are too short to fill on the display and fills the empty space with "0" pixels. If not centered, images are aligned with the top of the display. """ # Convert the image to black and white im = im.convert("L") width, height = im.size # Truncate the image height = min(height, display_height) # Work through the image for column in range(width): pixels = [] # Pad the bottom with zeros if too short (and centered) bottom_zeros = 0 if height < display_height and center: bottom_zeros = (display_height-height) / 2 for _ in range(bottom_zeros): pixels.append(0) # Add the pixel data (convert to black-and-white with simple threshold) for row in range(height): pixels.append(int(im.getpixel((column, height-row-1)) > 128)) # Pad the top half with zeros if too short for _ in range(display_height - height - bottom_zeros): pixels.append(0) yield pixels def text_to_lol(string, display_height, rotate = False, center = True, text_align="center", font=None, font_size=8): """ Generator function which uses PIL to render a text string for the display. Note that this function does *not* perform line-wrapping for lines which don't fit on the display. Long lines will be truncated, possibly mid-character. rotate rotates the text by 90 degrees center centers the message vertically (after rotation) on the display text_align selects the text alignment, can be "center", "left" or "right". font is the filename of a TrueType (ttf) font file. If not given a default font is used (for which the size cannot be selected). font_size gives the font size in points for the selected font. """ # Load the font if font is None: # Try to use the hd44780 font included with the package, falling back to the # system default font. try: pil_font = ImageFont.truetype(os.path.join(os.path.dirname(__file__),"hd44780.ttf"), font_size) except IOError: pil_font = ImageFont.load_default() else: pil_font = ImageFont.truetype(font, font_size) # Work out how big a string will be def get_string_size(string): im = Image.new("L", (1,1), 0) draw = ImageDraw.Draw(im) width, height = draw.textsize(string, font=pil_font) del draw del im return width,height # Split lines of message to render seperately lines = string.split("\n") # Work out size of each line line_sizes = [] for line in lines: line_sizes.append(get_string_size(line)) # Get the total image size width = max(w for (w,h) in line_sizes) height = sum(h for (w,h) in line_sizes) + len(lines) # Generate the image im = Image.new("L", (width, height), 0) draw = ImageDraw.Draw(im) for line_num, (line, (line_width,line_height)) in enumerate(zip(lines, line_sizes)): y = sum(h+1 for (w,h) in line_sizes[:line_num]) if text_align == "left": x = 0 elif text_align == "right": x = width - line_width elif text_align == "center": x = (width - line_width)/2 else: raise Exception("Unknown text alignment '%s'"%text_align) draw.text((x,y), line, 256, font=pil_font) del draw # Optionally rotate if rotate: im = im.transpose(Image.ROTATE_90) return pil_to_lol(im, display_height, center)
from functools import reduce def acceptList(): list = [] no=int(input("Enter the number of elements : ")) for i in range(no): el=int(input("Enter the elements:")) list.append(el) return list def filFun(n): return 70 <= n <= 90 def mapFun(n): return n+10 def redFun(n1,n2): return n1*n2 def main(): lst=acceptList() print("Input list : ",lst) filtered=list(filter(filFun,lst)) print("list after filter:",filtered) mapped=list(map(mapFun,filtered)) print("list after Map: ",mapped) reduced=reduce(redFun,mapped) print("output of reduce: ",reduced) if __name__ == '__main__': main()
#Write a program which accept N numbers from user and store it into List. Return Minimum #number from that List. #Input : Number of elements : 4 #Input Elements : 13 5 45 7 #Output : 5 if __name__ == '__main__': x = int(input("Enter number of elements: ")) list = [] for i in range(0,x): el=int(input("Enter element: ")) list.append(el) min=min(list) print(min) print("Min of list is", min)
#Write a program which accept number from user and return number of digits in that number. #Input : 5187934 Output : 7 #-------------------------------------------------------------------------------- def digit_count(n): print("Output : ",len(n)) print("Input :",end=" ") x=int(input()) digit_count(str(x))
print("\t\t\t Practice Problem 3.28") n = int(input('Enter number :')) for i in range(0,n): if i != n: print(i**2)
print("\t\t\t Practice Problem 3.37") def points(x1,y1,x2,y2): import math d = math.sqrt(((x2 - x1)**2) +((y2 - y1)**2)) if x2 == 0: print('The slope is infinity' + ' ' + 'and the distance is',d) else: s = ((y2 - y1) / (x2- x1)) print('The slope is',s,'and the distance is',d) coordinates = points(4,3,0,1) print(coordinates) coordinates2 = points(6,7,8,9) print(coordinates2)
print("\t\t\t Practice Problem 3.12") def negatives(number): neg_num = [] for i in number: if i < 0: neg_num.append(i) return neg_num x = negatives([1,3,-9,-10,-6,-8]) print(*x, sep ="\n")
print("Name: MUHAMMAD Usman Pervaiz") print("Roll no: 18B-006-CS") print("SECTION-A") print("\t\t\t PRACTICE PROBLEM 3.1(a)") age = int(input("Enter the age:")) if age > 62: print("You can get your pension benefits") else: print("Sorry")
import math def question2_all(number): toplam=0 #Sayıyının kucuk asal sayılarını bul asallar= all_primes(number) if len(asallar)==0: return False #Asal sayıları topla for i in range(len(asallar)): toplam= toplam + asallar[i] #Bu toplam verilen sayıya eşitse True değilse False if toplam==number: return True else: return False def question2_any(number): return True def all_primes(number): # return list(filter(is_prime, range(2, number))) rv = [] for i in range(2, number): if is_prime(i): rv.append(i) return rv def is_prime(number): if number == 1: return False s = int(math.sqrt(number)) + 1 for i in range(2, s): if number % i == 0: return False return True if __name__ == '__main__': for i in range(100): if question2_all(i): print(i)
import pandas as pd ''' Function to calculate average value of each column in the dataframe and return as a dictionary :param dataframe: dataframe to consider :param columns_list: list of columns to calculate mean for ''' class summary_of_dataframe(): def __init__(self, input_dataframe, columns_list): self.dataframe = input_dataframe self.columns_list = columns_list def get_average(self): average_dict = {} columns = [] if len(columns) == 0: columns = self.columns_list else: columns = self.dataframe.columns for i in columns: average_dict[i] = self.dataframe[i].mean() return average_dict ''' Function to calculate median value of each column in the dataframe and return as a dictionary :param dataframe: dataframe to consider :param columns_list: list of columns to calculate median for ''' def get_median(self): median_dict = {} columns = [] if len(columns) == 0: columns = self.columns_list else: columns = self.dataframe.columns for i in columns: median_dict[i] = self.dataframe[i].median() return median_dict ''' Function to calculate mode value of each column in the dataframe and return as a dictionary :param dataframe: dataframe to consider :param columns_list: list of columns to calculate mode for ''' def get_mode(self): mode_dict = {} columns = [] if len(columns) == 0: columns = self.columns_list else: columns = self.dataframe.columns for i in columns: mode_dict[i] = self.dataframe[i].mode() return mode_dict ''' Function to calculate variance of each column in the dataframe and return as a dictionary :param dataframe: dataframe to consider :param columns_list: list of columns to calculate range for ''' def get_variance(self): range_dict = {} columns = [] if len(columns) == 0: columns = self.columns_list else: columns = self.dataframe.columns for i in columns: range_dict[i] = self.dataframe[i].var() return range_dict ''' Function to calculate range value of each column in the dataframe and return as a dictionary :param dataframe: dataframe to consider :param columns_list: list of columns to calculate range for ''' def get_range(self): range_dict = {} columns = [] if len(columns) == 0: columns = self.columns_list else: columns = self.dataframe.columns for i in columns: range_dict[i] = self.dataframe[i].max() - self.dataframe[i].min() return range_dict
def startswith_capital_counter(words): counter = 0 for name in words: if name[0].isupper(): counter += 1 return counter
from collections import deque order_list = deque() for _n in range(int(input())): orders = input().strip().split() if orders[0] == "ISSUE": order_list.append(orders[1]) if orders[0] == "SOLVED": order_list.popleft() for order in order_list: print(order)
list_odd = [int(number) for number in input() if int(number) % 2 != 0] print(list_odd)
""" MÉTODO PARA ENCONTRAR AUTOVALORES DE UMA MATRIZ DADA """ import math as m import numpy as np def maxDiag(m, epsilon): """ FUNÇÃO QUE VERIFICA A CONDIÇÃO DE PARADA """ return abs(m[1][0]) > epsilon or abs(m[2][0]) > epsilon or abs(m[2][1]) > epsilon def autoValores(m): """ Função que cria o vetor com os autovalores """ return [m[0][0], m[1][1], m[2][2]] #Insira a Matriz aqui A = [[1, 2, 1], [-1, 3, 1], [0, 2, 2]] B = A #Insira o limitante para o erro aqui epsilon = 0.0001 s = c = R = Q = U = 0 i = 0 while maxDiag(A, epsilon): i+=1 if abs(A[1][0]) != 0 and maxDiag(A, epsilon): s = A[1][0] / m.sqrt(A[1][0]**2 + A[0][0]**2) c = A[0][0] / m.sqrt(A[1][0]**2 + A[0][0]**2) U = [[c, s, 0], [-s, c, 0], [0, 0, 1]] R = np.dot(U, A) Q = np.transpose(U) A = np.dot(R, Q) if abs(A[2][0]) != 0 and maxDiag(A, epsilon): s = A[2][0] / m.sqrt(A[2][0]**2 + A[0][0]**2) c = A[0][0] / m.sqrt(A[2][0]**2 + A[0][0]**2) U = [[c, 0, s], [0, 1, 0], [-s, 0, c]] R = np.dot(U, A) Q = np.transpose(U) A = np.dot(R, Q) if abs(A[2][1]) != 0 and maxDiag(A, epsilon): s = A[2][1] / m.sqrt(A[2][1]**2 + A[1][1]**2) c = A[1][1] / m.sqrt(A[2][1]**2 + A[1][1]**2) U = [[1, 0, 0], [0, c, s], [0, -s, c]] R = np.dot(U, A) Q = np.transpose(U) A = np.dot(R, Q) print("Iteração: ", i) print(A, "\n") print("AUTOVALORES:", autoValores(A)) print("Resultado Exato:", np.linalg.eigvals(B))
""" Função que calcula o maior autovalor de uma matriz """ import numpy as np def calculaErro(alpha2, alpha): return abs(alpha2 - alpha)/alpha2 #Insira a matriz Aqui A = [[1, 2, 1], [-1, 3, 1], [0, 2, 2]] #Insira a aproximação inicial aqui y0 = [1, 1, 1] i = 1 z1 = np.dot(A, y0) alpha = abs(max(z1, key=abs)) y1 = np.dot(1/alpha, z1) print("Iteração:", i) print("Yi =", y1) print("Alpha:", alpha, "\n") while(True): i+=1 z2 = np.dot(A, y1) alpha2 = abs(max(z2, key=abs)) y2 = np.dot(1/alpha2, z2) print("Iteração:", i) print("Yi =", y2) print("Alpha:", alpha2 , "\n") if(calculaErro(alpha2, alpha) < 0.00001): break y1 = y2 alpha = alpha2
import random number = random.randint (1,9) chances = 0 while chances < 5 : guess = int(input("enter your guess : ")) if guess == number : print("You won") break elif guess < number : print ("your guess was too low") else : print ("Your guess was too high") chances +=1 if not chances <5 : print ("You lose. The number is ",number)
import os, socket from ftplib import FTP ftp = FTP('') connection = False def start(ip, port): ftp.connect(ip, int(port)) ftp.login() print('Connected successfully...') connection = True def main(): global ftp response = input('>>> ') connection = False if 'CONNECT' in response: argument = response.split() if len(argument) == 3: start(argument[1], argument[2]) argument = [] main() else: print("CONNECT needs an IP address and port number!\n ") main() elif 'QUIT' in response: ftp.quit() print('Disconnecting from server...')
# -*- coding: utf-8 -*- # TO DO: make Pieces an abstract class class PiecesError(Exception): pass class Pieces(object): '''Preside of Pieces Objects''' piece_chars = ['P', 'N', 'B', 'R', 'Q', 'K'] @staticmethod def create(char, color): '''Given a char representation of a piece, and a color (w,b) Return instantiated Piece object of that type It will not yet have a postion ''' char = char if char == 'P': return Pawn(color) elif char == 'N': return Knight(color) elif char == 'B': return Bishop(color) elif char == 'R': return Rook(color) elif char == 'Q': return Queen(color) elif char == 'K': return King(color) else: raise PiecesError('Unrecognzied piece abbreviation: %s' % char) class PieceError(Exception): pass class Piece(object): '''Super class for all pieces ''' def __init__(self, color): if color not in ('w', 'b'): raise PiecesError('Unrecognized color: %s' % color) self.color = color self.postion = None self.moved = False def __repr__(self): return '%s:%s%s' %(self.color, self.char, self.position) @property def x(self): if self.position == 'x': return None return ord(self.position[0])-97 @property def y(self): if self.position == 'x': return None return int(self.position[1])-1 @property def opposite_color(self): return 'w' if self.color == 'b' else 'b' @property def char_glyph(self): return self.char.lower() if self.color == 'w' else self.char @property def glyph(self): if self.color == 'w': return self.glyphs[0] else: return self.glyphs[1] @property def data(self): glyph = self.glyphs[0] if self.color == 'w' else self.glyphs[1] return {'color': self.color, 'position': self.position, 'x': self.x, 'y': self.y, 'char': self.char, 'glyph': glyph, } class Pawn(Piece): # d f e # . char = 'P' value = 1 glyphs = ['♙', '♟'] @property def move_ops(self): '''Can move one move or two depending starting pos. Can move diagnal forward to capture ''' _move_ops = ['d1', 'e1', 'f1'] if (self.color == 'w' and self.position[1] == '2') or \ (self.color == 'b' and self.position[1] == '7'): _move_ops[-1] = 'f2' return _move_ops def __repr__(self): return '%s:%s' %(self.color, self.position) class Knight(Piece): # j k # i m # . # q n # p o char = 'N' value = 3 glyphs = ['♘', '♞'] move_ops = ['i1','j1','k1','m1','n1','o1','p1','q1'] class Bishop(Piece): # d e # . # g h char = 'B' value = 3 glyphs = ['♗', '♝'] move_ops = ['d*', 'e*', 'g*', 'h*'] class Rook(Piece): # f # r . l # b char = 'R' value = 5 glyphs = ['♖', '♜'] move_ops =['f*', 'b*', 'l*', 'r*'] class Queen(Piece): # d f e # r . l # g b h char = 'Q' value = 9 glyphs = ['♕', '♛'] move_ops = ['f*', 'b*', 'l*', 'r*', 'd*', 'e*', 'g*', 'h*'] class King(Piece): # d f e # r . l # g b h and y, z -> castle queen side, king side char = 'K' value = 0 glyphs = ['♔', '♚'] move_ops = ['f1', 'b1', 'l1', 'r1', # orthogonal 'd1', 'e1', 'g1', 'h1', # diaganal 'y1', 'z1'] # castle
class emp: def em1(self): self.n = raw_input(">") self.a = raw_input(">") print "Name: %r" %self.n + "Age: %r" %self.a def em2(self): self.n = raw_input(">") self.a = raw_input(">") print "Name: %r" %self.n + "Age: %r" %self.a class join: def joined(self): x = emp() print x.em1() print x.em2() b = emp() b.em1() b.em2() d = join() d.joined()
from runtime_calculator import * """A recursive linearithmic-time function. """ def f1(n): if n < 1: return for _ in range(n): pass f1(n // 2) f1(n // 2) """A recursive exponential-time function. """ def f2(n): if n < 1: return f2(n - 1) f2(n - 1) """A recursive linear-time function. """ def f3(n): if n < 1: return for _ in range(1000): pass f3(n // 2) f3(n // 2) # Expected: N log N x, y = test_algorithm(f1) plt.scatter(x, y, c='blue', label='f1', marker='.') runtime, func = find_best_function(x, y) graph_function(plt, x, func, 'b-') print('f1:', runtime) # Expected: 2^N x, y = test_algorithm(f2) plt.scatter(x, y, c='red', label='f2', marker='.') runtime, func = find_best_function(x, y) graph_function(plt, x, func, 'r-') print('f2:', runtime) # Expected: N x, y = test_algorithm(f3) plt.scatter(x, y, c='yellow', label='f3', marker='.') runtime, func = find_best_function(x, y) graph_function(plt, x, func, 'y-') print('f3:', runtime) plt.suptitle('Runtime of Divide-and-Conquer Function f1') plt.xlabel('Size of Input (N)') plt.ylabel('Runtime (seconds)') plt.legend(loc='upper left') plt.show()
print("Enter the limit ") n = int(input("")) t1 = 0 t2 = 1 for x in range(0,n): print(t1) newTerm=t1+t2 t1=t2 t2=newTerm x+=1
input = None while True: try: input = raw_input("Gimme a number >") num = int(input) except ValueError: print "'%s' isn't a number, bro" % input continue print "%f seems like a good number, thanks yo" % num
wörterbuch_deutsch = {"Apfel": "apple", "Birne": "pear", "Kirsche" : "cherry", "Melone": "melon", "Marille": "apricot", "Pfirsich": "peach"} wörterbuch_englisch = {"apple": "Apfel", "pear": "Birne", "cherry": "Kirsche", "apricot": "Marille", "peach": "Pfirsich"} running = True while running: try: auswahl = input("""Für die Übersetzung DE -> EN geben Sie 'D' oder 'd' ein. Für die Übersetzung EN -> DE geben Sie 'E' oder 'e' ein. Um das Programm zu beenden geben Sie 'B' oder 'b' ein. \033[1mIhre Auswahl:\033[0m""") if auswahl == 'D' or auswahl =='d': eingabe = input("Geben Sie ein deutsches Wort zum übersetzen ein:") eingabe = eingabe.capitalize() print("\033[1m Ihre Übersetzung ist: \033[0m", wörterbuch_deutsch[eingabe]) elif auswahl == 'E' or auswahl =='e': eingabe_1 = input("Geben Sie ein englisches Wort zum übersetzen ein:") eingabe_1 = eingabe_1.lower() print("\033[1m Ihre Übersetzung ist: \033[0m", wörterbuch_englisch[eingabe_1]) elif auswahl == 'B' or auswahl == 'b': running = False except KeyError: print("\033[1mBegriff nicht gefunden. Bitte um Neueingabe:\033[0m")
# SVR # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('data/Position_Salaries.csv') # Feature Selection X = dataset.iloc[:, 1:2].values # independent features as matrix y = dataset.iloc[:, 2].values # dependent features as vector ''' Since, we do have only 10 observations, we wont split the data into training and testing set. ''' ''' Since, SVR don't have feature scaling by default We will scale the feature for better fitting ''' from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() sc_y = StandardScaler() # Since we are fitting as well as transforming # we need to create seperate scaler for x and y X = sc_X.fit_transform(X) y = sc_y.fit_transform(y) # Fitting SVR to the dataset from sklearn.svm import SVR SVRRegressor = SVR(kernel = 'rbf') # since our data is non-linear, we could choose kernel among poly and gaussian(rbf) SVRRegressor.fit(X, y) # Visualing the SVR Results plt.scatter(X, y, color='red') plt.plot(X, SVRRegressor.predict(X), color='blue') plt.title('SVR Regressor') plt.xlabel('Position Level') plt.ylabel('Salary') plt.show() # Curve Smoothing # np.arrange Return evenly spaced values within a given interval. X_grid = np.arange(min(X), max(X), 0.1) # step of 0.1 X_grid = X_grid.reshape((len(X_grid)), 1) # matrix representation plt.scatter(X, y, color='red') plt.plot(X_grid, SVRRegressor.predict(X_grid), color = 'blue') plt.title('SVR Curve Smooting') plt.xlabel('Position Level') plt.ylabel('Salary') plt.show() # Predicting for new value 6.5 ''' Since we have used feature scaling, we need to feature scale the value whose y is to be predicted X should be matrix. so 6.5 should be converted to matrix representation ''' y_pred = SVRRegressor.predict(sc_X.transform(np.array([[6.5]]))) # We need to inverse transfrom y_pred to find the real value y_pred = sc_y.inverse_transform(y_pred)
# K Means Clustering # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv( 'data/Mall_Customers.csv' ) # Feature X = dataset.iloc[:, [3,4]].values # Using the elbow method to find the optimal number of clusters ''' Here we are plotting the elbow graph for 10 clusters While instantisating the kMeans , we could use init as 'random' but to avoid the random initialisation trap we are using 'k-means++' WCSS = Within Cluster Sum of Squares also called as intertia ''' from sklearn.cluster import KMeans wcss = [] for i in range( 1, 11 ): kmeans = KMeans( n_clusters = i, init = 'k-means++' ) kmeans.fit( X ) wcss.append( kmeans.inertia_ ) plt.plot( range( 1, 11 ), wcss ) plt.title( 'The Elbow Method' ) plt.xlabel( 'Number of Clusters' ) plt.ylabel( 'WCSS' ) plt.show() # Applying the K-means to the mall dataset with n_clusters = 5 ( from elbow graph ) kmeans = KMeans( n_clusters = 5, init = 'k-means++' ) y_kmeans = kmeans.fit_predict( X ) # Visualising the clusters plt.scatter( X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1' ) plt.scatter( X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2' ) plt.scatter( X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3' ) plt.scatter( X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4' ) plt.scatter( X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5' ) plt.scatter( kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow' ) plt.title( 'Clusters of clients' ) plt.xlabel( 'Annual Income (k$) ' ) plt.ylabel( 'Spending Score (1-100)' ) plt.legend() plt.show()
# Evolutionary Trees contains algorithms and methods used in determining phylogenetic inheritance of various species. # Main algos UPGMA and CLUSTALW from dataclasses import dataclass import FormattingET @dataclass class Node: age: int num: int label: str alignment: [] def __init__(self, child1=None, child2=None): self.child1 = child1 self.child2 = child2 #UPGMA algos def initializeMatrix(m, n): mtx = [[0 for x in range(n)] for y in range(m)] return mtx def initializeClusters(t): numNodes = len(t) numLeaves = (numNodes + 1) / 2 clusters = [0]*int(numLeaves) for i in range(int(numLeaves)): clusters[i] = t[i] return clusters def initializeTree(speciesNames): numLeaves = len(speciesNames) t = [Node]*(2*numLeaves - 1) for i in range(len(t)): vx = Node() if i < numLeaves: vx.label = speciesNames[i] else: vx.label = "Ancestor species" + str(i) vx.num = i t[i] = vx return t def countLeaves(v: Node): if v.child1 is None or v.child2 is None: return 1 return countLeaves(v.child1) + countLeaves(v.child2) def delClusters(clusters, row, col): del clusters[col] del clusters[row] return clusters def findMinElement(mtx): minRow = 0 minCol = 1 minElement = mtx[0][1] for row in range(0, len(mtx)): for col in range(row+1, len(mtx)): if mtx[row][col] < minElement: minRow = row minCol = col minElement = mtx[row][col] return minRow, minCol, minElement def delRowCol(mtx, row, col): del mtx[col] del mtx[row] for i in range(len(mtx)): del mtx[i][col] del mtx[i][row] return mtx def addRowCol(mtx, clusters, row, col): newRow = [0]*(len(mtx) + 1) for i in range(len(newRow) - 1): if i != row and i != col: size1 = countLeaves(clusters[row]) size2 = countLeaves(clusters[col]) avg = (size1*mtx[row][i] + size2*mtx[i][col]) / (size1 + size2) newRow[i] = avg mtx.append(newRow) for i in range(len(newRow) - 1): mtx[i].append(newRow[i]) return mtx def upgma(mtx, speciesNames): tree = initializeTree(speciesNames) clusters = initializeClusters(tree) numLeaves = len(mtx) for i in range(numLeaves, 2*numLeaves - 1): minElements = findMinElement(mtx) row = minElements[0] col = minElements[1] min = minElements[2] tree[i].age = min/2 tree[i].child1 = clusters[row] tree[i].child2 = clusters[col] mtx = addRowCol(mtx, clusters, row, col) clusters.append(tree[i]) mtx = delRowCol(mtx, row, col) clusters = delClusters(clusters, row, col) return tree #CLUSTALW algos def sumPairScores(align1, align2, idx1, idx2, match, mismatch, gap): alignment1 = ['']*len(align1) for i in range(len(align1)): alignment1[i] = align1[i][idx1] alignment2 = [''] * len(align2) for i in range(len(align2)): alignment2[i] = align2[i][idx2] score = 0.0 for char in alignment1: for char2 in alignment2: if char == '-' and char2 == '-': continue elif char == char2: score += match elif char != '-' and char2 != '-': score -= mismatch else: score -= gap return score def generateScoreTable(align1, align2, match, mismatch, gap, supergap): scoreTable = [[0 for j in range(len(align2[0]) + 1)] for i in range(len(align1[0]) + 1)] for i in range(len(scoreTable)): scoreTable[i][0] = i * (-supergap) for i in range(len(scoreTable[0])): scoreTable[0][i] = i * (-supergap) for i in range(1, len(align1[0]) + 1): for j in range(1, len(align2[0]) + 1): up = scoreTable[i-1][j] - supergap left = scoreTable[i][j-1] - supergap diag = scoreTable[i-1][j-1] + sumPairScores(align1, align2, i-1, j-1, match, mismatch, gap) scoreTable[i][j] = max(up, left, diag) return scoreTable def progressiveBacktrack(scoreTable, align1, align2, match, mismatch, gap, supergap): numRows = len(align1[0]) + 1 numCols = len(align2[0]) + 1 backtrack = [['' for i in range(numCols)] for j in range(numRows)] for i in range(1, numCols): backtrack[0][i] = "LEFT" for i in range(1, numRows): backtrack[i][0] = "UP" for i in range(1, numRows): for j in range(1, numCols): if (scoreTable[i][j] == scoreTable[i-1][j] - supergap): backtrack[i][j] = "UP" elif scoreTable[i][j] == scoreTable[i][j-1] - supergap: backtrack[i][j] = "LEFT" else: backtrack[i][j] = "DIAG" return backtrack def backtracker(string, backtrack, orientation): aligned = "" row = len(backtrack) - 1 col = len(backtrack[0]) - 1 while(row != 0 or col != 0): k = len(string) if backtrack[row][col] == "UP": if (orientation == "top"): aligned = "-" + aligned elif orientation == "side": aligned = str(string[k - 1]) + aligned string = string[:k - 1] row -= 1 elif backtrack[row][col] == "LEFT": if (orientation == "side"): aligned = "-" + aligned elif orientation == "top": aligned = str(string[k-1]) + aligned string = string[:k-1] col -= 1 else: aligned = str(string[k-1]) + aligned string = string[:k-1] row -= 1 col -= 1 return aligned def outputProgressiveAlign(align1, align2, backtrack): a = [[""] for i in range(len(align1) + len(align2))] for i in range(len(align1)): a[i] = backtracker(align1[i], backtrack, "side") for j in range(len(align1), len(align2) + len(align1)): a[j] = backtracker(align2[j - len(align1)], backtrack, "top") return a def progressiveAlign(align1, align2, match, mismatch, gap, supergap): scoreTable = generateScoreTable(align1, align2, match, mismatch, gap, supergap) backtrack = progressiveBacktrack(scoreTable, align1, align2, match, mismatch, gap, supergap) opt = outputProgressiveAlign(align1, align2, backtrack) return opt def clustalw(guideTree, dnaStrings, match, mismatch, gap, supergap): for i in range(len(dnaStrings)): guideTree[i].alignment = [dnaStrings[i]] for j in range(len(dnaStrings), len(guideTree)): child1 = guideTree[j].child1 child2 = guideTree[j].child2 guideTree[j].alignment = progressiveAlign(child1.alignment, child2.alignment, match, mismatch, gap, supergap) return guideTree[len(guideTree) - 1].alignment #main if __name__ == "__main__": print("UPGMA Test") mtx = [[0, 3, 4, 3], [3, 0, 4, 5], [4, 4, 0, 2], [3, 5, 2, 0]] labels = ["H", "C", "W", "S"] tree = upgma(mtx, labels) print("CLUSTALW Test") #cats = ["USA", "CHN", "ITA"] mtxreturn = FormattingET.readMatrixFromFile("Datasets/Input/Test-Example/distance.mtx") mtx1 = mtxreturn[0] labels1 = mtxreturn[1] t = upgma(mtx1, labels1) match = 1.0 mismatch = 1.0 gap = 1.0 supergap = 6.0 dnaMap = FormattingET.readDNAStringsFromFile("Datasets/Input/Test-Example/RAW/toy-example.fasta") keyvalues = FormattingET.getKeyValues(dnaMap) newLabels = keyvalues[0] newDnaStrings = keyvalues[1] dnaStrings = FormattingET.rearrangeStrings(labels1, newLabels, newDnaStrings) align = clustalw(t, dnaStrings, match, mismatch, gap, supergap) FormattingET.writeAlignmentToFile(align, labels1, "Datasets/Output/Test-Example", "toy.aln") print(align)
t0 = 'Questionário' print(t0.center(50, "*")) altura_p = 1.60 idade_p = 18 altura = input('qual sua altura:\n') idade = input('qual sua idade:\n') if altura > '1.60' and idade > '18': print('Voce esta apto para o exercito') else: print('voce n esta apto para o exercito')
# A simple line example. from bokeh.plotting import figure, show x = [1, 2, 3, 4, 5] y1 = [4, 5, 4, 5, 4] y2 = [3, 4, 3, 4, 3] y3 = [2, 3, 2, 3, 2] # Create a plot p = figure(title="Line example", x_axis_label="X axis", y_axis_label="Y axis") # Add a "glyph" to it p.line(x=x, y=y1, line_width=3, line_color="blue", legend_label="Temperature") p.line(x=x, y=y2, line_width=3, line_color="green", legend_label="Temperature") p.line(x=x, y=y3, line_width=3, line_color="red", legend_label="Temperature") # Show the results show(p)
# http://www.practicepython.org/exercise/2014/05/21/15-reverse-word-order.html def reverse(cadena): lista_cad = cadena.split() lista_rev = [ lista_cad[len(lista_cad) - a - 1] for a in range(len(lista_cad)) ] return " ".join(lista_rev) # cadena = input ("Introduce una cadena, preferiblemente compuesta por varias palabras: ") cadena_rev = reverse(cadena) print (cadena_rev)
# http://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html from random import randint def estaDentroDe(num, lista): for i in lista: if (i == num): return True a = [] b = [] res = [] for i in range(20): #GENERAR DOS LISTAS ALEATORIAS numa = randint(0,20) numb = randint(0,20) a.append(numa) b.append(numb) # a.sort() b.sort() for i in range(20): #RECORRER LAS DOS LISTAS EN BUSCA DE REPETICIONES repe = False for j in range(20): #repe = False if(a[i] == b[j]): if (not estaDentroDe(a[i],res)): res.append(a[i]) # res.sort() print (a) print (b) print (res)
def intersect(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ """x = set(nums1) y = set(nums2) return x.intersection(y)""" y = list() x = dict() for i in nums1: if x.__contains__(i): x[i]+=1 else: x.update({i: 1}) for i in nums2: if x.__contains__(i): if x[i]>1: x[i] -= 1 else: x.pop(i) y.append(i) return y def intersect_opt(nums1, nums2): large=nums1 small=nums2 if len(large)<len(small): nums1,nums2=large,small d={} for n in nums1: if n in d: d[n]+=1 else: d[n]=1 s=[] for n in nums2: if n in d and d[n]>0: s+=[n] d[n]-=1 return s if __name__ == '__main__': nums1 = [1, 2, 3, 4, 0, 5, 6, 7, 0] nums2 = [4,8,4,8,1,1,1,1,1,1] print(intersect(nums1, nums2)) print(intersect_opt(nums1,nums2))
# Doubly Linked List - Very similar to singly linked, however these have prev pointer and a tail node. # - Move left, to previous node, form a fiven node # - Move immediately to the last node class DoubleNode: def __init__(self, data, next= None, prev = None): self.data = data self.next = next self.prev = prev class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def display_linked(self): print("Show list data:") current_node = self.head while current_node: #print(current_node.next) print(current_node.data) #print(current_node.prev) current_node = current_node.next print("*"*50) # two cases to consider def append(self, data): new_node = DoubleNode(data) # is it empty? if self.head is None: new_node.prev = self.head new_node.next = None self.head = new_node self.tail = new_node # there are items in the list else: # may be easier way with new tail function self.tail.next = new_node new_node.prev = self.tail self.tail = self.tail.next # probe = self.head # while probe.next != None: # probe = probe.next # new_node.prev = probe # probe.next = new_node def prepend(self, data): new_node = DoubleNode(data) if self.head is None: print(self.head) new_node.prev = None self.head = new_node self.tail = self.head else: print(self.head) new_node.next = self.head new_node.prev = None self.head = new_node def delete_value(self, value): current_node = self.head while current_node is not None: if current_node.data == value: # if it's not the first or last element if current_node.prev is not None and current_node.next is not None: current_node.prev.next = current_node.next current_node.next.prev = current_node.prev # if it first element elif current_node.prev is None: # otherwise we have no prev (it's None), head is the next one, and prev becomes None self.head = current_node.next current_node.next.prev = None else: self.tail = current_node.prev.next current_node.prev.next = None current_node = current_node.next print(self.head) print(self.tail) #inserting node within the linked list def insert_node(self, index, data): # is linked list empty or index less than 0 new_node = DoubleNode(data) if self.head is None: new_node.prev = None self.head = new_node self.tail = self.head elif index <= 0: new_node.next = self.head print(self.head.next) new_node.prev = None self.head = new_node else: # search for node at position index -1 or last position pointer = self.head while index > 1 and pointer.next != None: pointer = pointer.next index -= 1 # insert new node after node at position index -1 or last position #pointer.next(data, pointer.next) if pointer.next is None: new_node.next = pointer.next new_node.prev = pointer pointer.next = new_node self.tail = new_node else: new_node.next = pointer.next pointer.next.prev = new_node pointer.next = new_node new_node.prev = pointer def reverse(self): new_linked = DoublyLinkedList() pointer = self.tail count = 0 self.display_linked() while pointer.prev is not None: print(self.head, self.tail) count+=1 print(count) print(pointer.data) new_linked.append(pointer.data) print(pointer.prev) print(pointer.next) pointer = pointer.prev new_linked.display_linked() return new_linked def howard_rev(self): current = self.tail while current is not None: temp = current.next current.next = current.prev current.prev = temp current = current.next temp = self.head self.head = self.tail self.tail = temp def testing(): d_list = DoublyLinkedList() d_list.append('First Node Data') d_list.append([1, 2, 'howdy']) d_list.append('C') d_list.display_linked() #testing() def testing_2(): d_list = DoublyLinkedList() #head = DoublyLinkedList.append(1) #tail = head #for data in range(2, 6): #tail.next = DoublyLinkedList.append(data) #tail = tail.next #pointer = tail #while d_list.display_linked() #testing_2() def test_prepend(): d_list = DoublyLinkedList() d_list.append('First Node Data') #print(d_list.head, d_list.tail) d_list.prepend('test') d_list.prepend('#2 test') #print(d_list.head, d_list.tail) d_list.display_linked() # test_prepend() def test_delete_value(): d_list = DoublyLinkedList() d_list.append('A') d_list.append('B') d_list.append('C') d_list.display_linked() d_list.delete_value('C') d_list.display_linked() #test_delete_value() def test_insert(): d_list = DoublyLinkedList() d_list.append('Soon #2') d_list.prepend('test') #d_list.prepend('#2 test') #d_list.display_linked() d_list.display_linked() print(d_list.head, d_list.tail) d_list.insert_node(2, "NEW FIRST") d_list.display_linked() print(d_list.head, d_list.tail) #test_insert() def test_reverse(): d_list = DoublyLinkedList() d_list.append('first') d_list.append('Soon #2') d_list.prepend('test') d_list.insert_node(2, "NEW FIRST") d_list.display_linked() d_list.howard_rev() d_list.display_linked() test_reverse()
# this class will represent a singly linked structure class Node(): def __init__(self, data, next = None): # instantiates a Node with a default next of none self.data = data self.next = next # This linkedlist class will instantiate Node objects and we'll add methods to this class to add functionality class LinkedList: def __init__(self): self.head = None def display_linked(self): current_node = self.head while current_node: print(current_node.data) current_node = current_node.next # add things to our linked list def append(self, data): # instantiate a new node newNode = Node(data) # is there something in our linked list yet? if self.head is None: #could be => if self.head: (since None would be False) self.head = newNode # there are node(s) in our linked list else: # intialize our probe pointer current_node = self.head # is probe at the end of our linked list? while current_node.next != None: current_node = current_node.next current_node.next = newNode # add Node to beginning def prepend(self, data): # instantiate a new node newNode = Node(data) newNode.next = self.head self.head = newNode #inserting node within the linked list def insert_node(self, index, data): # is linked list empty or index less than 0 if self.head is None or index <= 0: self.head = Node(data, self.head) # find our position to insert else: # search for node at position index -1 or last position pointer = self.head while index > 1 and pointer.next != None: pointer = pointer.next index -= 1 # insert new node after node at position index -1 or last position #pointer.next(data, pointer.next) pointer.next = Node(data, pointer.next) # remove a node def delete_node(self, index): # is this the only node if index <= 0 or self.head.next is None: removed_node = self.head.data self.head = self.head.next return removed_node else: pointer = self.head while index > 1 and pointer.next.next != None: pointer = pointer.next index -= 1 removed_node = pointer.next.data pointer.next = pointer.next.next return removed_node def replace_node(self, target_item, new_data): pointer = self.head while pointer != None and target_item != pointer.data: pointer = pointer.next if pointer != None: # meaning it equals SOMETHING, stopped before the end pointer.data = new_data return True else: return False def get_length(self): count = 0 pointer = self.head while pointer != None: count += 1 pointer = pointer.next return count def get_reverse(self): # length = self.get_length() pass def get_copy(self): pointer = self.head new_linked = LinkedList() while pointer != None: new_linked.append(pointer.data) pointer = pointer.next return new_linked def test_apppend(): linked_list = LinkedList() linked_list.append("A") linked_list.append("Hello, I am the second Node!") linked_list.display_linked() # test_apppend() def test_prepend(): linked_list = LinkedList() linked_list.append("A") linked_list.append("Hello, I am the second Node!") linked_list.prepend('I should be at the begining') #linked_list.insert_node(0, "newer start") linked_list.display_linked() # test_prepend() def test_insert(): linked_list = LinkedList() linked_list.append("A") linked_list.append("Hello, I am the second Node!") linked_list.prepend('I should be at the begining') linked_list.insert_node(2, 'inserted') # if we enter a too large index, it will add at end linked_list.insert_node(24, 'last') linked_list.display_linked() # test_insert() def test_delete(): linked_list = LinkedList() linked_list.append("A") linked_list.append("Hello, I am the second Node!") linked_list.prepend('I should be at the begining') #linked_list.insert_node(2, 'inserted') #linked_list.insert_node(24, 'last') linked_list.delete_node(2) linked_list.display_linked() # test_delete() def test_last_few(): linked_list = LinkedList() linked_list.append("A") linked_list.append("#2!") linked_list.prepend('I should be at the begining') linked_list.insert_node(2, 'inserted') linked_list.delete_node(3) linked_list.replace_node('A', "replaced") print(linked_list.get_length()) linked_list.display_linked() new_linked = linked_list.get_copy() new_linked.display_linked() #linked_list.append("only in old") #new_linked.append("only in new") #linked_list.display_linked() #new_linked.display_linked() # test_last_few() ''' Circular Linked List - Special Case of Singly liked list - Insertion and removal of the first node are special cases of the insert ith and remove ith operations on a singly linked list. These are special because the head pointer must be reset. you can use circular linked list with a dummy header node. Contains a link from the last node to the first node in the structure ''' class CircularLinked: def __init__(self): self.head = None def append(self, data): if not self.head: self.head = Node(data) self.head.next = self.head else: new_node = Node(data) pointer = self.head while pointer.next != self.head: pointer = pointer.next pointer.next = new_node new_node.next = self.head def display_linked(self): current_node = self.head print(current_node.data) while current_node.next != self.head: current_node = current_node.next print(current_node.data) def Howard_reverse(self): current = self.head prev = None next = None while current is not None: next = current.next current.next = prev prev = current current = next # c_linked = CircularLinked() # c_linked.append(5) # c_linked.append(6) # c_linked.append(7) # c_linked.display_linked()
''' ***************** Linked Structures *************************** A linked Structure is a concrete data type that implements many types of collections, including lists. As the names implies, a linked structure consists of items that are linked to other items. The two that we'll go over are Singly Linked Structures and Doubly-Linked Structures - Head Link - the first item of a linked structure - Tail Link - an external link in a doubly linked structure to access the last item directly - Empty Link - the absence of a link, indicated by the slash in the diagram - The last item in either strucure has no link to the next item - Node - The basic unit of representation in a linked structure - comprised of two items - A Data Item - A link to the next node in the structure In python, we set up nodes and linked strucutres by using references to objects ''' # this class will represent a singly linked structure class Node(): def __init__(self, data, next = None): # instantiates a Node with a default next of none self.data = data self.next = next # This linkedlist class will instantiate Node objects and we'll add methods to this class to add functionality class LinkedList: def __init__(self): self.head = None def example(): # just an empty link node1 = None # A node containing data and empty link node2 = Node('A', None) # a node with a link node3 = Node('B', node2) print(node3.data) def test_node(): head = None # Add 5 nodes to the begining of the the linked structure for count in range(5, 0, -1): head = Node(count, head) # print the contents of the structure while head != None: print(head.data) # print(head.next) head = head.next # test_node() """ - One pointer, head, generates the linked structure. This pointer is manipulated in such a way that the most recently inserted item is alwaysat the beginining of the structure - When the data is displayed, they appear in the reverse order of their insertion - Also, when the data are displayed, the head poointer is reset to the next node, until the head pointer becomes none. Thus, at the end of this process, the nodes are effectively deleted from the linked structure. They are no longer available to the program and are recycled during the next garbage collection """ """ ***************** Operations on Linked Structures *************************** """ """ - Arrays are already index based, because the indices are an integral part of the array structure - We must emulate index-based operations on a linked structure by manipulating link within the structure. """ def create_nodes(): head = None # Add 5 nodes to the begining of the the linked structure for count in range(1, 6): head = Node(count, head) return head def print_node(head): # print the contents of the structure while head != None: print(head.data) # print(head.next) head = head.next """ - Traversal - uses a temporary pointer variable named probe. THis variable is initialized to the link structure's head pointer and then controls a loop as follows: """ # probe = head # while probe != None: # # other code here # probe = probe.next """ - Searching - The sequential search of a linked structure resembles a traversal in that you must start at the first node and follow links until you reach a sentinel - two possible sentinels, empty link( end of structure), or you find your item """ # probe = head # while probe != None and target_item != probe.data: # probe = probe.next # if probe != None: # meaning it equals SOMETHING, stopped before the end # # if you found your item, some code # else: # # your target isn't in the the list def test_search(head, target_item = 3): probe = head while probe != None and target_item != probe.data: probe = probe.next if probe != None: # meaning it equals SOMETHING, stopped before the end print(target_item, '=', probe.data) else: print(target_item, '= Not there') # print_node(create_nodes()) # print() # test_search(create_nodes(),4) # test_search(create_nodes(),10) """ - Accessing our ith item Similar to a sequesntial search, we can't go straight to i start at the first node and count the number of links until you reach the ith node Link """ # index = (what item # you are looking for) # # Assumes 0 <= index < n # probe = head # while index > 0: # probe = probe.next # index -= 1 # return probe.data def test_access_index(head): index = 0 # (what item # you are looking for) # Assumes 0 <= index < n probe = head while index > 0: probe = probe.next index -= 1 return probe.data # print_node(create_nodes()) # print(test_access_index(create_nodes())) """ Replacement = Also, employs the traversal pattern. you search for a given item or position and replace that item when found. If If you no item is found then no replacement happend and the operation returns False. If replacement occurs the operation returns True. """ # probe = head # while probe != None and target_item != probe.data: # probe = probe.next # if probe != None: # meaning it equals SOMETHING, stopped before the end # probe.data = newItem # return True # else: # return False def test_replace(head, target_item=2): probe = head while probe != None and target_item != probe.data: probe = probe.next if probe != None: # meaning it equals SOMETHING, stopped before the end probe.data = 10 return True, probe.data else: return False #print_node(create_nodes()) #print(test_replace(create_nodes())) """ Inserting at the Begining - better than linear complexity on a linked structure """ # head = Node(newItem, head) """ Inserting at the End - Consider two cases The head pointer is None, so the head pointer is set to the new node The head pointer is not None, so the code searches for the last node and aims its next pointer at the new node. """ # newNode = Node(newItem) # next=None by default, so you don't need to add it # if head is None: # head = newNode # else: # probe = head # while probe.next != None: # probe = probe.next # probe.next = newNode def test_add_end_node(head): newNode = Node(10) # next=None by default, so you don't need to add it if head is None: head = newNode else: probe = head while probe.next != None: probe = probe.next probe.next = newNode return head #print_node(test_add_end_node(create_nodes())) """ Removing at beginning - this operation returns the removed item """ # Assumes at least one node in the structure # removed_item = head.data # head = head.next # return removed_item """ Removing at the End - Two cases to consider There is just one node. THe Head pointer is set to None. There is a node before the last node. the code searchs for the second-to last node and sets its next pointer to None """ # removed_item = head.data # if head.next is None: # head = None # else: # probe = head # while probe.next.next != None: # probe = probe.next # removed_item = probe.next.data # probe.next = None # return removed_item def remove_from_end(head): removed_item = head.data if head.next is None: head = None else: probe = head while probe.next.next != None: probe = probe.next removed_item = probe.next.data probe.next = None return removed_item # print_node(create_nodes()) # print('\n', remove_from_end(create_nodes())) """ Insert at any position - two cases to consider 1. the node's next pointer is None. This means that i>=n, so you should place the new item at the end of the linked structure 2. the node's next pointer is not None. that means that 0 < i < n, so you must place the new item between the node at position i-1 and the node at i """ # index = 2 # if head is None or index <= 0: # head = Node(newItem, head) # else: # # search for node at position index -1 or the last position # probe = head # while index > 1 and probe.next != None: # probe = probe.next # index -= 1 # # Insert new node after node at posotion i -1 or the last position # probe.next = Node(newItem, probe.next) def test_insert_node(head, index = 2): if head is None or index <= 0: head = Node(10, head) else: # search for node at position index -1 or the last position probe = head while index > 1 and probe.next != None: #print(index, probe.data) probe = probe.next index -= 1 # Insert new node after node at posotion i -1 or the last position probe.next = Node(10, probe.next) return head # print_node(test_insert_node(create_nodes())) """ Removing an item - Consider 3 cases 1. i<= 0 - you can use the code to remove the first item 2. 0<i<n - you can search for the node at position i-1, as in insertion, and remove the following Node 3. i>= n - you remove the last node """ # #Assume that the linked strucutre has at least one item # if index <= 0 or head.next is None: # removed_item = head.data # head = head.next # return removed_item # else: # # search for node at position index -1 or next to last position # probe = head # while index > 1 and probe.next.next != None: # probe = probe.next # index -= 1 # removed_item = probe.next.data # probe.next = probe.next.next # return removed_item def test_remove_any(head, index = 3): #Assume that the linked strucutre has at least one item if index <= 0 or head.next is None: removed_item = head.data head = head.next #return removed_item else: # search for node at position index -1 or next to last position probe = head while index > 1 and probe.next.next != None: probe = probe.next index -= 1 removed_item = probe.next.data probe.next = probe.next.next #return removed_item print(removed_item, '\n') return head # print_node(test_remove_any(create_nodes())) def get_len(head): count = 0 while head != None: count += 1 head = head.next return count def get_len_recur(head): if head is None: return 0 return 1 + get_len_recur(head.next) # print(get_len(create_nodes())) # print(get_len_recur(create_nodes())) #def class_len_recur(self, node) # if node is None: # return 0 # return 1 + (self.class_len_recur(node.next)) #print(class_len_recur(llist.head)) def node_swap(head, key1, key2): current = head if current is None: print('Error, empty list') while head.next != None: head = head.next if key1 == head.data: while True: pass key1_next = head.next key1_prev = head.prev def swap_nodes(head, key1, key2): if key1 == key2: return head prev_1 = None curr_1 = head #(self.head) while curr_1 and curr_1.data != key1: prev_1 = curr_1 curr_1 = curr_1.next # print(prev_1.data) # print(curr_1.data) prev_2 = None curr_2 = head # or self.head while curr_2 and curr_2.data !=key2: prev_2 = curr_2 curr_2 = curr_2.next if not curr_2 or not curr_1: return #'Error' # check if the previous pointer is blank, and set head if prev_1: prev_1.next = curr_2 else: #self.head = prev_1 head = curr_2 # same check if prev 2 is if prev_2: prev_2.next = curr_1 else: #self.head = prev_2 head = curr_1 # a, b = b, curr_1.next, curr_2.next = curr_2.next, curr_1.next return head #print_node(swap_nodes(create_nodes(), 2, 3)) def print_helper(node, name): if node is None: print(name + ": None") else: print(name + " : " + str(node.data)) def reverse_single(head): prev = None curr = head #self.head while curr != None: next = curr.next # save next curr.next = prev # reverse print_helper(prev, "PREV") print_helper(curr, "CURR") print_helper(next, "NEXT") print('\n') prev = curr # advance prev curr = next # advance next #self.head = prev return prev #print_node(create_nodes()) #print_node(reverse_single(create_nodes())) def reverse_recursive(head): def reverse_recursive(cur, prev): if not cur: return prev next = cur.next cur.next = prev prev = cur cur = next return reverse_recursive(cur, prev) head = reverse_recursive(cur = head, prev = None) # self.head return head print_node(create_nodes()) print_node(reverse_recursive(create_nodes()))
# this prints the running times for problem sizes that double using a single loop import time def benchmark1(): problem_size = 10000000 for count in range(5): start = time.time() # the start of the slogrithm work = 1 for x in range(problem_size): work += 1 work -= 1 # the end of the algorithm elapsed = time.time() - start print(f'{problem_size} - {elapsed}') problem_size *=2 #first() """ Output 10000000 - 1.6076991558074951 20000000 - 2.979032039642334 40000000 - 5.941112995147705 80000000 - 12.23102855682373 160000000 - 23.845795392990112""" def benchmark2(): problem_size = 1000 # significatnly reduced!!! for count in range(5): start = time.time() # the start of the slogrithm work = 1 for j in range(problem_size): for k in range(problem_size): work += 1 work -= 1 # the end of the algorithm elapsed = time.time() - start print(f'{problem_size} - {elapsed}') problem_size *=2 """ Output : 1000 - 0.0817406177520752 2000 - 0.3869640827178955 4000 - 1.554842233657837 8000 - 5.020118474960327 16000 - 19.252073049545288""" #second() def counting(): problem_size = 1000 # significatnly reduced!!! for count in range(5): number = 0 # the start of the slogrithm work = 1 for j in range(problem_size): for k in range(problem_size): number += 1 work += 1 work -= 1 # the end of the algorithm print(f'{problem_size} - {number}') problem_size *=2 # counting() """ Output : 1000 - 1000000 2000 - 4000000 4000 - 16000000 8000 - 64000000 16000 - 256000000""" # Prints the number of calls of a recursive Fibonacci function with problem sizes that double # from collections import Counter """this import wouldn't work... had to comment out code... """ def fib(n, counter): # count the number of calls of the fib func # Counter.increment() if n < 3: return 1 else: return fib(n-1, counter) + fib(n-2, counter) def count_fib(): for count in range(5): problemSize = 2 counter = 0 # Counter() # The start of the algorithm fib(problemSize, counter) # the end of the algorithm print(problemSize, counter) problemSize *= 2 #count_fib()
data = {'city':'Москва', 'temperature':'20'} print(data['city']) data['temperature'] = int(data['temperature']) - 5 data print(data.get('country', 'Russia')) data['date'] = '27.05.2019' data print(len(data))
""" Clase que simula una página de memoria. Atributos: - bit_memory: indicador de almacenamiento de la memoria - frame: memoria física en la que se encuentra - ID: número de página del proceso """ class Page(): # Bit_memory = 1 page is in M (main memory) # Bit_memory = 0 page is in S (swapping memory) bit_memory = 0 frame = 0 ID = 0 def __init__(self, ID, frame, bit_memory): self.bit_memory = bit_memory self.frame = frame self.ID = ID def update_page(self, frame, bit_memory): self.frame = frame self.bit_memory = bit_memory
'''num = 12 if num > 5 : print("Bigger than 5") if num <= 47 : print("Between 6 & 47") x = 4 if x == 5 : print("Its 5"); else: print("Its not 5") num = 7 if num == 5 : print("Number is 5") else : if num == 11 : print("Number is 11") else : if num == 7 : print("Number is 7") else : print("Number isn't 5,11 or 7") num = 7 if num == 5 : print("Number is 5") elif num == 11 : print("Number is 7") elif num == 7 : print("Number is 7") else: print("Number isn't 5,11 or 7") a = 400 b = 200 if ( a >= 100 and a < 200) else 300 print(b) status = 1 msg = "Logout" if status == 1 else "Login" print(msg) for i in range(10): print(i) else : print("Done") ''' a = 1 b = 1 c = 5 d = 10 if ( a == b and d > c ): print("a and b are equal and d is greater than c")
# 打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。 for i in range(100,1000): if int(str(i)[0]) ** 3 + int(str(i)[1]) ** 3 + int(str(i)[2]) ** 3 == i: print(i)
# 古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? """ 2,2,4,6,10,16,26... """ def rabbits_sum(time): r_1 = 2 r_2 = 2 if time <= 2: return 2 else: for i in range(time-3): r_1 += r_2 r_2 += r_1 if time % 2 == 0: return r_2 else: return r_1 if __name__ == '__main__': time = int(input("输入第几个月:")) print(rabbits_sum(time))
# 斐波那契数列 # 斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。 # def fblist(x): # y = l[x - 3] + l[x - 2] # return y # # if __name__ == '__main__': # x = int(input("请输入一个整数(>=3):")) # f0 = 0 # f1 = 1 # l = [f0, f1] # while len(l) < x: # l.append(fblist(len(l)+1)) # print(l) def fib(x): fibs = [0, 1] if x <=2: return fibs[0:x] else: for i in range(2,x): fibs.append(fibs[-1] + fibs[-2]) return fibs if __name__ == '__main__': x = int(input("请输入一个正整数:")) print(fib(x))
# 类的创建和基本使用 # 这个self是约定命名,可以是任何变量名 class Person: def set_name(self, name): self.name = name def get_name(self): return self.name def greet(self): print("Hello, world! I'm {}.".format(self.name)) p1 = Person() p1.set_name("Jonh") p2 = Person() p2.set_name("Lee") p1.greet() # Hello, world! I'm Jonh. p2.greet() # Hello, world! I'm Lee. print(p1.get_name()) # Jonh # 可以直接对属性进行设置 p1.name = "Mark" print(p1.name) # Mark # 类方法的调用,也可以使用类名的方式调用,我理解在类上的调用应该与此等价 Person.greet(p1) # Hello, world! I'm Mark. # Python中没有私有属性,可以通过以下方法来达到私有属性的效果 class Sec : __name = "J" # 两个下划线开头的属性或者方法,实际上都会添加下划线开头加类名的前缀 def set_name(self, name): self.__name = name def get_name(self): return self.__name def greet(self): print("Hello, world! I'm {}.".format(self.__name)) s = Sec() s.greet() # Hello, world! I'm J. s.__name = "K" s.greet() # Hello, world! I'm J. s._Sec__name = "K" # 双下划线开头的会添加前缀,实际中不推荐这样使用 s.greet() # Hello, world! I'm K. # 也可以对一个不存在的属性赋值 s.__k = "s" # 单下划线也被视为不能直接修改约定,在使用from module import *中不会导入以下划线开头的名称 # 类名空间下的成员是所有对象共享的,也是独立于对象的,如果对象的属性没有定义,则使用类的属性 print(Sec._Sec__name) # J # 所以类也可以被当成命名空间来使用,因为在类中可以直接执行语句 class C: print("Class C being defined") # 以上输出 Class C being defined # 继承的基本使用 class Base: def init(self): self.p = "base" def show(self): print("I'm ", self.p) # 在定义类时添加括号表示继承的基类 class Extend(Base): def init(self): self.p = "extend" b = Base() b.init() b.show() # I'm base e = Extend() e.init() e.show() # I'm extend # 与继承相关的方法 # 是否是继承关系 print(issubclass(Extend, Base)) # True # 获取基类,由于支持多重继承,所以还一个属性__bases__ print(Extend.__base__) # <class '__main__.Base'> # object是所有类的基类 print(Base.__base__) # <class 'object'> # 以下两个都返回True,判断对象是否是某个类 print(isinstance(Extend(), Base)) print(isinstance(Extend(), Extend)) # 获取对象属于哪个类 print(Extend().__class__) # <class '__main__.Extend'> # 多重继承 # 如果写成Super(Base, Extend)则无法运行,因为不满足MRO,可阅读参考文献 # 所以在多重继承中注意两个超类含有同一个属性或者方法的情况 class Super(Extend, Base): pass s = Super() s.init() s.show() # I'm extend # 判断某一个对象是否有某一个属性,以及这个属性是否可调用 print(hasattr(s, "show")) # True # getattr的第三个参数表示不存在时的默认值,如果不提供默认值且不存在,则报错 print(getattr(s, "p")) # extend # callable检查是否可调用 print(callable(getattr(s, "show", None))) # True # 设置对象的属性,返回None setattr(s, "p1", "p1val") # 获取所有属性 print(s.__dict__) # {'p': 'extend', 'p1': 'p1val'} # 抽象基类 # 在Python中并没有提供原生的语法来支持抽象类,但可以使用abc这个官方模块解决此问题 from abc import ABC, abstractclassmethod class Talker(ABC): @abstractclassmethod def talk(self): pass # 以下语句会报错TypeError: Can't instantiate abstract class Talker with abstract methods talk # t = Talker() # 如果只是继承了而没有实现抽象方法,还是会报错 class Foo(Talker): pass # t = Foo() class Knigget(Talker): def talk(self): print("Ni") k = Knigget() # 一般的抽象类应用场景中会有isinstance判断 if isinstance(k, Talker): k.talk() # Ni # 但这与Python的鸭子类型的编程思想,如果一个类有talk方法,但没有继承Talker,则在此场景中没有办法调用talk # register提供了将某一类注册为另外一个类子类的办法 class Herring: def talk(self): print("Blue") h = Herring() print(isinstance(h, Talker)) # False # 将Herring 注册为Talker的子类 Talker.register(Herring) print(isinstance(h, Talker)) # True print(issubclass(Herring, Talker)) # True # 这种做法的问题是,如果Herring没有实现talk方法,则此时调用talk方法会直接报错,如下: class Clam: pass Talker.register(Clam) c = Clam() if isinstance(c, Talker): c.talk() # 这里将报错,因为Clam没有实现talk方法,但又是Talker的子类
#coding=utf-8 filename=raw_input("get a file name:>>>") txt=open(filename) print "your file name is :%s\n" % filename print txt.read() #就算是只要写一个文件名,但是也要注意路径和格式,这里的文件就在当前python程序所在目录,所以 #可以直接写,但是格式txt的后缀还是要加的
from typing import Dict """ Utility functions that don't fit anywhere else. """ def get_string_with_spacing(data: Dict[str, str]) -> str: """ Gets a string representation of a list of key/value pairs (as OrderedDictionary) with proper spacing between key/values. :param data: A Dictionary containing key/value pairs. :return: A string representation of the Dictionary. """ max_width = max([len(k) for k in data]) return '\n'.join(('{} = {}'.format(k.ljust(max_width), v) for k, v in data.items())) + '\n'
import os import csv # Setting path for the csv budget data pybankcsv = os.path.join("Resources", "budget_data.csv") #Let's create lists in order to store data profit = [] monthly_changes = [] date = [] #Placing required variables count = 0 total_profit = 0 total_change_profits = 0 initial_profit = 0 #Let's open the csv budget data file with open(pybankcsv, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csvreader) for row in csvreader: #Let's use count to count the number of months in the dataset count = count +1 #It will be needed when collecting the greatest increase and decrease in profits date.append(row[0]) #Let's append the profit information and calculate the total profit profit.append(row[1]) total_profit = total_profit - int(row[1]) #Let's calculate the average change in profits from month to month followed by calculating the average change in profits final_profit = int(row[1]) monthly_change_profits = final_profit - initial_profit #Let's store these monthly changes in a list monthly_changes.append(monthly_change_profits) total_change_profits = total_change_profits + monthly_change_profits initial_profit = final_profit #Let's calculate the average change in profits average_change_profits = (total_change_profits/count) #Let's find the max and in change in profits and corresponding dates to these changes greatest_increase_profits = max(monthly_changes) greatest_decrease_profits = min(monthly_changes) increase_date = date[monthly_changes.index(greatest_increase_profits)] decrease_date = date[monthly_changes.index(greatest_decrease_profits)] print("----------------------------------------------------------------") print("Financial Analysis") print("----------------------------------------------------------------") print("Total Months: " + str(count)) print("Total Profits: " + "$" + str(total_profit)) print("Average Change: " + "$" + str(int(average_change_profits))) print("Greatest Increase in Profits: " + str(increase_date) + " ($" + str(greatest_increase_profits) + ")") print("Greatest Decrease in Profits: " + str(decrease_date) + " ($" + str(greatest_decrease_profits) + ")") print("----------------------------------------------------------------") with open('financial_analysis.txt', 'w') as text: text.write("--------------------------------------------------------------\n") text.write(" Financial Analysis" + "\n") text.write("---------------------------------------------------------------\n\n") text.write(" Total Months: " + str(count) + "\n") text.write(" Total Profits: " + "$" + str(total_profit) +"\n") text.write(" Average Change: " + '$' + str(int(average_change_profits)) + "\n") text.write(" Greatest Increase in Profits: " + str(increase_date) + " ($" + str(greatest_increase_profits) + ")\n") text.write(" Greatest Decrease in Profits: " + str(decrease_date) + " ($" + str(greatest_decrease_profits) + ")\n") text.wrtie("--------------------------------------------------------------\n")
# Exercício 2: Para exercitar nossa capacidade de abstração, vamos modelar # algumas partes de um software de geometria. Como poderíamos modelar um objeto # retângulo? # Nome da abstração: retângulo # atributos: base, altura # métodos: # - calcular_area (base * altura), # - calcular_perimetro ((base + altura) * 2) class Retangulo: def __init__(self, base, altura): self.base = base self.altura = altura def calcular_area(self): return self.base * self.altura def calcular_perimetro(self): return (self.base + self.altura) * 2 retangulo_1 = Retangulo(10, 5) area_retangulo_1 = retangulo_1.calcular_area() perimetro_retangulo_1 = retangulo_1.calcular_perimetro() print(area_retangulo_1, perimetro_retangulo_1)
# Crie um algoritmo não recursivo para contar quantos números pares existem em # uma sequência numérica (1 a n). def count_even_numbers(n): count = 0 for number in range(1, n + 1): if number % 2 == 0: count += 1 return count print(count_even_numbers(10))
# Exercício 7: Utilize o dicionário criado no exercício 5. Para as chaves # ímpares, não queremos mais mapear para o seu sobro, mas sim, para o seu # triplo. Consulte o método keys() e atualize o seu dicionário para a nova # regra. my_dict = {x: x * 2 for x in range(3, 21)} my_keys = my_dict.keys() for k in my_keys: if k % 2 != 0: my_dict[k] = k * 3 print(my_dict)
class Conjunto: def __init__(self): self.values = [False for index in range(1001)] def add(self, item): if not self.values[item]: self.values[item] = True def __str__(self): # retorno: uma string que representa o seu objeto string = '{' for index, is_in_set in enumerate(self.values): if is_in_set: string += str(index) + ', ' string = string[:-2] + '}' return string def __contains__(self, item): # retorno: True, caso o elemento faça parte. False, caso o elemento # não faça parte. return self.values[item] def union(self, conjuntoB): # retorno: outro objeto Conjunto com união do próprio objeto com o # conjuntoB new_conjunto = Conjunto() for index in range(1001): if self.values[index] or conjuntoB.values[index]: new_conjunto.add(index) return new_conjunto def intersection(self, conjuntoB): # retorno: outro objeto Conjunto com intersecção do próprio objeto com # o conjuntoB new_conjunto = Conjunto() for index in range(1001): if self.values[index] and conjuntoB.values[index]: new_conjunto.add(index) return new_conjunto def difference(self, conjuntoB): # retorno: outro objeto Conjunto com os elementos que tem em A e não em B new_conjunto = Conjunto() for index in range(1001): if self.values[index] and not conjuntoB.values[index]: new_conjunto.add(index) return new_conjunto def issubset(self, conjuntoB): # retorno: True se o A for subconjunto de B e False se não for for index in range(1001): if self.values[index] and not conjuntoB.values[index]: return False return True def issuperset(self, conjuntoB): # retorno: True se A for um superConjunto de B e False se não for for index in range(1001): if conjuntoB.values[index] and not self.values[index]: return False return True # my_conj = Conjunto() # for item in [0, 10, 100, 1000]: # my_conj.add(item) # print(my_conj.__str__()) # print(my_conj.__contains__(101)) conjA = Conjunto() for item in range(11): conjA.add(item) conjB = Conjunto() for item in range(10, 21): conjB.add(item) conjC = Conjunto() conjC.add(10) conjC.add(14) conjC.add(16) conjC.add(11) # print(conjA.union(conjB)) # print(conjA.intersection(conjB)) # print(conjA.difference(conjB)) print(conjB.issuperset(conjC))
# escrita file = open("arquivo.txt", mode="w") LINES = ["Olá\n", "mundo\n", "belo\n", "do\n", "Python\n"] file.writelines(LINES) file.close() # leitura file = open("arquivo.txt", mode="r") for line in file: print(line) # não esqueça que a quebra de linha também é um caractere da file.close() # não podemos esquecer de fechar o arquivo
class Node: def __init__(self, value): self.value = value # 🎲 Dado a ser armazenado self.next = None # 👉 Forma de apontar para outro nó def __str__(self): return f"Node(value={self.value}, next={self.next})"
def countdown(n): # nome da função e parâmetro if n == 0: # condição de parada print('FIM!') else: print(n) countdown(n - 1) # chamada de si mesma com um novo valor countdown(5)
def is_odd(number): 'Retorna True se um número é verdadeiro, senão False.' return number % 2 != 0 def divide(a_number, other_number): "Retorna a divisão de a_number por other_number" return a_number / other_number
class User: def __init__(self, name, email, password): """ Método construtor da classe User. Note que o primeiro parâmetro deve ser o `self`. Isso é uma particularidade de Python, vamos falar mais disso adiante!""" self.name = name self.email = email self.password = password # Função que reseta a senha, ela fica dentro da classe User e pode ser chamada # através do objeto que foi instanciado através desta classe def reset_password(self): print("Envia email de reset de senha") # Para invocar o método construtor, a sintaxe é NomeDaClasse(parametro 1, parametro 2) # Repare que o parâmetro self foi pulado -- um detalhe do Python. meu_user = User("Valentino Trocatapa", "valentino@tinytoons.com", "Grana") print(meu_user) print(meu_user.name) print(meu_user.email) print(meu_user.password) # A variável `meu_user` contém o objeto criado pelo construtor da classe User! # Chamada da função através do objeto 'meu_user' criado através da classe User # Agora este objeto tem acesso não só a todas as chaves da classe mas também às # funções. meu_user.reset_password()
# Exercício 5: Considere que a cobertura da tinta é de 1 litro para cada # 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam # R$ 80,00. Crie uma função que retorne dois valores em uma tupla contendo a # quantidade de latas de tinta a serem compradas e o preço total a partir do # tamanho de uma parede(em m²). def ink_value(wall_size): number_of_cans = (wall_size // 54) if wall_size % 54 != 0: number_of_cans += 1 can_price = number_of_cans * 80.00 return (number_of_cans, can_price) print(ink_value(55))
# Lazy algorithm for solving dynamic connectivity problem # Data structure # Integer array id[] of size N # Interpretation - array representing set of trees, each entry in array contains reference to parent # id[i] is parent of i # root of i is id[id[i]] - keep going until the value doesn't change class QuickUnion: # n being the number of nodes def __init__(self, n): self.id = [] for x in range(n): self.id.append(x) # Given an id, i, find the root node def root(self, i): # While the node i and its root are not equal, follow the tree to its root while i != self.id[i]: # Path compression self.id[i] = self.id[id[i]] # Have each node in path point to its grandparent (halving path length) i = self.id[i] return i # Given two ids, return true if they are connected, false if not # Two nodes are connected if their root nodes are the same def find(self, first_id, second_id): if self.root(first_id) == self.root(second_id): return True else: return False # Given two nodes, connect them # Two nodes are connected by setting id of second_id's root to the id of first_id's root def union(self, first_id, second_id): first_root = self.root(first_id) second_root = self.root(second_id) self.id[second_id] = first_root
#!/usr/bin/env python3 # coding: utf-8 """ The Minigame module consists of three widgets on a parent widget. Two of them are DrawWidgets, which are used to let the players draw unistrokes. The third is the TemplateWidget. It will show a template, which the players need to draw. Author: Thomas Oswald """ from PyQt5 import QtWidgets, QtCore, QtGui from recognizer import Recognizer from random import randint from bt_input import Device class DrawWidget(QtWidgets.QFrame): """ The DrawWidget is responsible for displaying an area in which the users can draw. """ # pyqtsignal for the recognition at the end of each drawing interaction finished_unistroke = QtCore.pyqtSignal(object, str, str) def __init__(self, name, width, height, parent=None): super(DrawWidget, self).__init__(parent) self.width = width self.height = height self.setMouseTracking(True) self.recognize_flag = False self.click_flag = False self.positions = [] self.cursor_radius = 10 self.cursor_pos = None self.path = QtGui.QPainterPath() self.init_ui(name, width, height) self.name = name self.just_started = False self.t_name = "" def init_ui(self, name, width, height): self.setAutoFillBackground(True) self.setFrameShape(QtWidgets.QFrame.Box) self.setFixedSize(width, height) self.setStyleSheet( "background-color:white; border:1px solid rgb(0, 0, 0);") self.cursor_pos = QtCore.QPoint(width / 2, height / 2) self.update() def set_cursor(self, point): self.cursor_pos = point def draw_cursor(self, qp): if self.cursor_pos is not None: qp.drawEllipse(self.cursor_pos, self.cursor_radius, self.cursor_radius) # Overwritten method responsible for painting def paintEvent(self, event): qp = QtGui.QPainter() qp.begin(self) qp.drawPath(self.path) self.draw_cursor(qp) qp.end() def on_template_selected(self, t_name): self.t_name = t_name # callback function for the button press and release event # Pyqtsignal emitting def on_click(self, btn, is_down): if btn == Device.BTN_A: self.click_flag = not self.click_flag self.just_started = True if not self.click_flag: print("emitted") self.finished_unistroke.emit( self.positions, self.name, self.t_name) # on move callback for position update of wiimote def on_move(self, x, y): if self.click_flag: pos = QtCore.QPoint(x, y) # self.mapToGlobal(QtCore.QPoint(x, y)) self.set_cursor(pos) if self.just_started: self.just_started = False self.path.moveTo(pos) self.positions.append((pos.x(), pos.y())) self.update() return self.positions.append((pos.x(), pos.y())) self.path.lineTo(pos) self.update() """ This methods will not be needed. Just for testing. TODO: DELETE # mouse moves with mouse or with set_cursor def mouseMoveEvent(self, event): if self.click_flag: self.click_flag = False self.path.moveTo(event.pos()) self.positions.append((event.pos().x(), event.pos().y())) self.update() return self.positions.append((event.pos().x(), event.pos().y())) self.path.lineTo(event.pos()) self.update() def mousePressEvent(self, event): self.path.moveTo(event.pos()) self.update() def mouseReleaseEvent(self, event): self.finished_unistroke.emit(self.positions, self.name, self.t_name) self.positions = [] """ class TemplateWidget(QtWidgets.QFrame): """ The TemplateWidget will randomly show a unistroke painting at the start of the minigame. """ template_selected = QtCore.pyqtSignal(str) def __init__(self, width, height, parent=None): super(TemplateWidget, self).__init__(parent) self.width = width self.height = height self.init_ui(width, height) self.path = QtGui.QPainterPath() def init_ui(self, width, height): self.setStyleSheet( "background-color:white; border:1px solid rgb(0, 0, 0);") self.setFixedSize(width, height) self.setAutoFillBackground(True) # This function draws a random template in the widget. def draw(self): template = self.get_random_template().split(":") t_name = template[0] points = eval(template[1]) self.template_selected.emit(t_name) center = (self.width / 2, self.height / 2) self.path.moveTo(points[0][0] + center[0], points[0][1] + center[0]) for point in points[1:]: self.path.lineTo(point[0] + center[0], point[1] + center[0]) self.update() def paintEvent(self, event): qp = QtGui.QPainter() qp.begin(self) qp.drawPath(self.path) qp.end() # This method selects a template randomly. def get_random_template(self): lines = [] with open("strokes.map", "r") as strokes: lines = strokes.readlines() if len(lines) > 0: return lines[randint(0, len(lines) - 1)] return None class MiniGameWidget(QtWidgets.QWidget): """ The MiniGameWidget is the parent of the three other widgets. It coordinates them and connects the bluetooth input to the DrawWidgets. After the two players drew the line, each of those will be moved to a $1 recognition algorithm. The unistroke, which is the closest to the template, will be recognized and as such the user will win the minigame. """ on_end = QtCore.pyqtSignal(str) def __init__(self, size, devices, parent=None): super(MiniGameWidget, self).__init__(parent) self.width, self.height = size self.scores = [] self.player, self.conductor, self.template = self.init_ui() rec_1 = Recognizer() rec_2 = Recognizer() rec_1.set_callback(self.on_result) rec_2.set_callback(self.on_result) self.template.template_selected.connect( self.player.on_template_selected) self.template.template_selected.connect( self.conductor.on_template_selected) self.player.finished_unistroke.connect( lambda points, name, t_name: self.on_rec(rec_1, points, name, t_name)) self.conductor.finished_unistroke.connect( lambda points, name, t_name: self.on_rec(rec_2, points, name, t_name)) self.devices = None if devices is not None and len(devices) > 0: self.connect_devices(devices, self.player, self.conductor) self.devices = devices self.template.show() self.player.show() self.conductor.show() self.show() self.setHidden(False) self.template.draw() def hide(self): if self.devices is not None: for device in self.devices: device.unregister_callbacks() self.template.setParent(None) self.player.setParent(None) self.conductor.setParent(None) self.setHidden(True) self.close() def init_ui(self): self.showFullScreen() layout = QtWidgets.QHBoxLayout(self) player = DrawWidget("player", self.width, self.height, self) layout.addWidget(player, alignment=QtCore.Qt.AlignLeft) template = TemplateWidget(self.width, self.height, self) layout.addWidget(template, alignment=QtCore.Qt.AlignCenter) conductor = DrawWidget("conductor", self.width, self.height, self) layout.addWidget(conductor, alignment=QtCore.Qt.AlignRight) self.setLayout(layout) return (player, conductor, template) def on_rec(self, rec, points, name, t_name): print("begin rec") rec.recognize(points, name, t_name) # This method gets the result of the recognition processes. # After receiving two results, it will decide who won. def on_result(self, template, score, name): print("received result") self.scores.append({"name": name, "score": score}) if len(self.scores) > 1: if abs(self.scores[0]["score"]) < abs(self.scores[1]["score"]): self.on_end.emit(self.scores[0]["name"]) else: self.on_end.emit(self.scores[1]["name"]) def connect_devices(self, devices, player, conductor): if len(devices) > 0: devices[0].register_click_callback(player.on_click) devices[0].register_move_callback(player.on_move) if len(devices) > 1: devices[1].register_click_callback(conductor.on_click) devices[1].register_move_callback(conductor.on_move)
a=0 b=1 '''for a in range(a,5):''' while a<10: print(a,end="") a,b=b,a+b print()
import csv import os csv_file = "budget_data.csv" with open('budget_data.csv') as budget_data: readCSV = csv.reader(budget_data) next(readCSV) revenue = [] date = [] rev_change = [] for row in readCSV: print("0: ", row[0],", 1:",row[1]) revenue.append(float(row[1])) date.append(row[0]) print("Financial Analysis") print("---------------------") print("Total Months:", len(date)) print("Total Revenue: $", sum(revenue)) for i in range(1, len(revenue)): rev_change.append(revenue[i] - revenue[i - 1]) avg_rev_change = sum(rev_change) / len(rev_change) max_rev_change = max(rev_change) min_rev_change = min(rev_change) max_rev_change_date = str(date[rev_change.index(max(rev_change))]) min_rev_change_date = str(date[rev_change.index(min(rev_change))]) print("Average Revenue Change: $", round(avg_rev_change)) print("Greatest Increase in Revenue:", max_rev_change_date, "($", max_rev_change, ")") print("Greatest Decrease in Revenue:", min_rev_change_date, "($", min_rev_change, ")")
# To use this script use python3 run this script from "nand2tetris/projects/". # Fill the next variable with your and your partner details. PAIR = True # Change to 'False' if you work alone. # First FIRST_USER_NAME = "david" FIRST_FULL_NAME = "David Wies" FIRST_ID = "311511802" FIRST_EMAIL = "david.weis@mail.huji.ac.il" # Second SECOND_USER_NAME = "omer" SECOND_FULL_NAME = "Omer Shacham" SECOND_ID = "20403472" SECOND_EMAIL = "omer.shacham@mail.huji.ac.il" ends = {'.py', '.jack'} # Write the ends of the type of files that you want to submit here. submit = {'VMtranslator', 'Makefile'} dont_submit = {} # Write the names of files you dont want to submit here. # Note: This isn't an offical program and may contain bugs or create the files in different format # than the course staff want. The use of this program is on your own responseility. # Create by David Wies # -------------------------------------------- Don't touch the code --------------------------------------------- import os import sys import tarfile def to_add(filename): for end_file in ends: if filename.endswith(end_file) and not dont_add(filename): return True return filename in submit def dont_add(filename): for name in dont_submit: if filename == name: return True return False def run_over_folder(address, to_do_readme, indentation=0): folder_files = '' to_submit = '' files = os.listdir(address) for file_name in files: if os.path.isdir(address + '/' + file_name): inner_files, inner_submit = run_over_folder(address + '/' + file_name, to_do_readme, indentation + 1) if len(inner_submit) > 0: folder_files += '\t' * indentation + file_name + ':\n' folder_files += inner_files to_submit += inner_submit elif to_add(file_name): if to_do_readme: description = input('Enter description for ' + file_name + ' (enter "--skip" to skip the file): ') if description == '--skip': continue folder_files += '\t' * indentation + file_name + ' - ' + description + '\n' to_submit += address + '/' + file_name + ' ' return folder_files, to_submit if __name__ == "__main__": ex_number = input('Which project do you want to submit? ') while not ex_number.isdigit(): if ex_number == 'exit': exit(0) ex_number = input("The given input wasn't number, please enter the number of" ' the project that you want to submit? ') if len(ex_number) == 1: ex = '0' + str(ex_number) else: ex = str(ex_number) do_readme = not (os.path.isfile(ex + '/README')) readme = None if not do_readme: overwrite_readme = input('Do you want to overwrite the readme? (Enter "yes" or "no") ') if overwrite_readme == 'yes': do_readme = True if do_readme: try: readme = open(ex + '/README', 'w') except FileNotFoundError: print('There is no project with that name.', file=sys.stderr) exit(-1) if PAIR: readme.write(FIRST_USER_NAME + ', ' + SECOND_USER_NAME + '\n') readme.write('===============================================================================' + '\n') readme.write(FIRST_FULL_NAME + ', ID ' + FIRST_ID + ', ' + FIRST_EMAIL + '\n') readme.write(SECOND_FULL_NAME + ', ID ' + SECOND_ID + ', ' + SECOND_EMAIL + '\n') else: readme.write(FIRST_USER_NAME + '\n') readme.write('===============================================================================' + '\n') readme.write(FIRST_FULL_NAME + ', ID ' + FIRST_ID + ', ' + FIRST_EMAIL + '\n') readme.write('===============================================================================' + '\n' + '\n') readme.write(' Project ' + ex_number + ' - An Python File' + '\n') readme.write(' -----------------------\n\n\n') readme.write('Submitted Files\n---------------\n') readme.write('README - This file.\n') files_to_readme, files_to_submit = run_over_folder(ex, do_readme) if do_readme: readme.write(files_to_readme) remark = input('Enter the remarks separated by hash tag: ') if len(remark) > 0: readme.write('\n\nRemarks\n-------\n') remarks = remark.split('#') for remark in remarks: readme.write('* ' + remark + '\n') readme.close() os.chdir(ex) tar = tarfile.open('project' + ex_number + '.tar', 'w') files_to_submit = files_to_submit.split(' ')[:-1] for file in files_to_submit: tar.add(file[len(ex) + 1:]) tar.add('README') tar.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 21 16:06:23 2019 @author: marissaeppes This script takes a base url for the api call, a sting of variables that need to be included in the call to retrieve complete data, and an end addition to the url. The functions makes the api call. """ import requests BASE_URL = "http://api.census.gov/data/2014/ase/csa?get=" END_URL = "&for=us:*" VARS_STR = 'EMP,EMP_S,EMPSZFI,EMPSZFI_TTL,ETH_GROUP,ETH_GROUP_TTL,FIRMPDEMP,\ FIRMPDEMP_S,GEO_ID,GEO_TTL,GEOTYPE,MSA,NAICS2012,NAICS2012_TTL,\ PAYANN,PAYANN_S,RACE_GROUP,RACE_GROUP_TTL,RCPPDEMP,RCPPDEMP_S,\ RCPSZFI,RCPSZFI_TTL,SEX,SEX_TTL,ST,VET_GROUP,VET_GROUP_TTL,YEAR,\ YIBSZFI,YIBSZFI_TTL' VARS_STR = VARS_STR.replace(" ", "") def call_api(base_url=BASE_URL, end_url=END_URL, vars_str=VARS_STR): """ Concatenates base url, string of variables, and url ending, passes complete url into api request, returns json object. """ url = base_url + vars_str + end_url response = requests.get(url) results = response.json() return results
names="rohan","raju","ramu" print(type(names)) for naam in names: print(naam)
# 1 list1 = ["CA", "NJ", "RI"] list2 = ["California", "New Jersey", "Rhode Island"] combined = {list1[i]:list2[i] for i in range(len(list1))} print("combined: ", combined) # 2 person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]] person_dict = {k:v for k,v in person} print("person_dict: ", person_dict) # 3 vowels = "aeiou" vowels_dict1 = {k:0 for k in vowels} print("method 1: ",vowels_dict1) vowels_dict2 = {}.fromkeys(vowels, 0) print("method 2: ", vowels_dict2) # 4 ascii dictionary ascii_dict = {count: chr(count) for count in range(65, 91)} print(ascii_dict)
from typing import Iterable, Tuple from advent_util import read_input, write_output from functools import reduce DAY="02" def parse_instruction(accumulator: Tuple[int, int], instruction: str) -> Tuple[int, int]: match instruction.split(): case ["forward", x]: return tuple(map(sum, zip(accumulator, (int(x), 0)))) case ["down", x]: return tuple(map(sum, zip(accumulator, (0, int(x))))) case ["up", x]: return tuple(map(sum, zip(accumulator, (0, -int(x))))) def part_one(instructions: Iterable[str]) -> int: final_position = reduce(parse_instruction, instructions, (0,0)) return final_position[0] * final_position[1] def parse_instruction_revised(accumulator: Tuple[int, int, int], instruction: str) -> Tuple[int, int, int]: match instruction.split(): case ["forward", x]: return tuple(map(sum, zip(accumulator, (int(x), int(x) * accumulator[2], 0)))) case ["down", x]: return tuple(map(sum, zip(accumulator, (0, 0, int(x))))) case ["up", x]: return tuple(map(sum, zip(accumulator, (0, 0, -int(x))))) def part_two(instructions: Iterable[str]) -> int: final_position = reduce(parse_instruction_revised, instructions, (0,0,0)) return final_position[0] * final_position[1] if __name__ == "__main__": instructions = list(read_input(DAY)) write_output(DAY, 1, part_one(instructions)) write_output(DAY, 2, part_two(instructions))
from typing import Iterable def read_input(day: int) -> Iterable[str]: """ Reads input file from inputs folder Arguments: day -- the day contained in input file with this name format: day_{day}.txt """ filename = f"inputs/day_{day}.txt" with open(filename, "r") as f: for line in f: yield line def write_output(day: int, part: int, output: str) -> None: """ Writes output to outputs folder Arguments: day -- the day for the output file part -- the part from the daily challenge output -- what to write on the file """ filename = f"outputs/day_{day}_part_{part}.txt" with open(filename, "w") as f: f.write(str(output))
#!/bin/python3 # Challenge: https://www.hackerrank.com/contests/hack-the-interview-iv-apac/challenges/maximum-or-1 import math import os import random import re import sys # # Complete the 'getNumberOfIntegers' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. STRING L # 2. STRING R # 3. INTEGER K # def getNumberOfIntegers(L, R, K): num_list = [] for num in range(int(L)+1,int(R)+1): num_str = str(num) num_str_len = len(num_str) if num_str.count('0') == num_str_len - K: num_list.append(num_str) #print(num_str, end=' ') return len(num_list) # Write your code here if __name__ == '__main__': #fptr = open(os.environ['OUTPUT_PATH'], 'w') L = input() R = input() K = int(input().strip()) ans = getNumberOfIntegers(L, R, K) #fptr.write(str(ans) + '\n') #fptr.close() print(ans)
''' The Mandelbrot set is the set of complex numbers c for which the function f( z ) = z**2 + c does not diverge when iterated from z = 0 , i.e., for which the sequence f( 0 ) , f ( f ( 0 ) ) etc., remains bounded in absolute value. for each sample point c , whether the sequence f( 0 ) , f ( f ( 0 ) ) ,... goes to infinity (in practice -- whether it leaves some predetermined bounded neighborhood of 0 after a predetermined number of iterations). Treating the real and imaginary parts of c as image coordinates on the complex plane, pixels may then be coloured according to how soon the sequence | f ( 0 ) | , | f ( f ( 0 ) ) | ,... crosses an arbitrarily chosen threshold, with a special color (usually black) used for the values of c for which the sequence has not crossed the threshold after the predetermined number of iterations (this is necessary to clearly distinguish the Mandelbrot set image from the image of its complement). If c is held constant and the initial value of z —denoted by z0 is variable instead, one obtains the corresponding Julia set for each point c in the parameter space of the simple function. ''' from PIL import Image from numpy import complex, array import colorsys # setting the width of the output image as 1024 WIDTH = 1024 # a function to return a tuple of colors # as integer value of rgb def rgb_conv(i): color = 255 * array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5)) return tuple(color.astype(int)) # function defining a mandelbrot def mandelbrot(x, y): c0 = complex(x, y) c = 0 for i in range(1, 1000): if abs(c) > 2: return rgb_conv(i) c = c * c + c0 return (0, 0, 0) # creating the new image in RGB mode img = Image.new('RGB', (WIDTH, int(WIDTH / 2))) pixels = img.load() for x in range(img.size[0]): # displaying the progress as percentage print("%.2f %%" % (x / WIDTH * 100.0)) for y in range(img.size[1]): pixels[x, y] = mandelbrot((x - (0.75 * WIDTH)) / (WIDTH / 4), (y - (WIDTH / 4)) / (WIDTH / 4)) # to display the created fractal after # completing the given number of iterations img.show() #img.save('file.png')