text
stringlengths
37
1.41M
# EXERCÍCIO Nº 03- LISTA 06 - STRINGS print('\n Nome na Vertical') print('#################\n') nome=input('Insira o seu nome: ').upper() for letra in nome: print('o',letra)
# EXERCÍCIO Nº 15- LISTA 04 - LISTAS print('\nNotas e cálculos') print('################\n') lista=[] nota=0 while nota!=-1: nota=float(input('Insira uma nota (número inteiro): ')) if nota !=-1: lista.append(nota) qtde=len(lista) soma=sum(lista) média=soma/qtde a=0 acima_da_média=0 acima_de_sete=0 for i in lista: if lista[a]>média: acima_da_média+=1 if lista[a]>7: acima_de_sete+=1 a+=1 print('A quantidade de valores é de:',qtde) print('Notas =',lista) lista.reverse() print('Notas inversa =', lista) print('A soma das notas é de: ',soma) print('A média das notas é de: ',média) print('As quantidade das notas acima da média é de:',acima_da_média) print('A quantidade das notas acima de sete é de:',acima_de_sete) print('Fim do programa')
#EXERCÍCIO Nº 25 - LISTA 02 - ESTRUTURA DE DECISÃO print('Perguntas sobre um crime') print('########################') a=input('Você telefonou para a vítima? (S/N): ') b=input('Você esteve no local do crime? (S/N): ') c=input('Você mora perto da vítima? (S/N): ') d=input('Você devia para a vítima? (S/N): ') e=input('Você já trabalhou com a vítima? (S/N): ') if a.upper()=='S': a=1 else: a=0 if b.upper()=='S': b=1 else: b=0 if c.upper()=='S': c=1 else: c=0 if d.upper()=='S': d=1 else: d=0 if e.upper()=='S': e=1 else: e=0 soma=a+b+c+d+e print(soma) if soma == 2: print('Pessoa Suspeita') elif soma>=3 or soma<=4: print('Cumplice') elif soma==5: print('Assassino') else: print('Inocente')
# EXERCÍCIO Nº 21- LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nNúmero Primo') print('############\n') lista=[2,3,5,7,11,13,17] a=0 número_inteiro=0 while número_inteiro>=0: número_inteiro =float(input('Insira um número inteiro >0: ')) while número_inteiro!=int(número_inteiro): print('O número deve ser inteiro') número_inteiro =float(input('Insira um número inteiro >0: ')) número_inteiro=int(número_inteiro) divisores = 0 for i in range(1, número_inteiro): if número_inteiro % i == 0: divisores=divisores+1 if divisores>1: break if divisores > 1: print("O número não é primo") elif número_inteiro == 1: print("O número não é primo") else: print('O número é primo') nova_entrada = input('Deseja inserir outro número(S/N): ').upper() while 'SN'.find(nova_entrada) < 0: print('Digite S ou N') nova_entrada = input('Deseja inserir outro número(S/N): ').upper() if nova_entrada == 'S': a += 1 else: break
#EXERCÍCIO Nº 12 - LISTA 02 - ESTRUTURA DE DECISÃO print('Folha de pagamento') print('##################') valor_hora=float(input('Insira o valor da hora trabalhada: R$ ')) horas_trabalhada=float(input('Insira a quantidade de horas trabalhadas no mês: ')) salário_bruto=valor_hora*horas_trabalhada #Tabela do Imposto de Renda if salário_bruto<=900: IR=0 elif salário_bruto <=1500: IR=0.05 elif salário_bruto <=2500: IR=0.10 else: IR:0.20 if IR >0: IR1=IR*100 else: IR1='Isento' INSS=0.10 FGTS=0.11 #Salário líquido, bruto e descontos: if IR>0: salário_liquído=salário_bruto-(salário_bruto*IR+salário_bruto*INSS) desconto_IR=salário_bruto*IR1/100 total_descontos=(salário_bruto*IR+salário_bruto*INSS) else: salário_liquído = salário_bruto - (salário_bruto * INSS) desconto_IR=0.00 total_descontos = salário_bruto * INSS print('⃝ SALÁRIO BRUTO: (',valor_hora,'*',horas_trabalhada,') : R$ ',salário_bruto ) print('⃝ (-) IR (',IR1,'$) : R$ ',desconto_IR ) print('⃝ (-) INSS (',INSS*100,'$) : R$ ',salário_bruto*INSS) print('⃝ FGTS (',FGTS*100,'$) : R$ ',salário_bruto*FGTS) print('⃝ TOTAL DE DESCONTOS : R$ ',total_descontos) print('⃝ SALÁRIO LÍQUIDO : R$ ',salário_liquído)
#EXERCÍCIO Nº 01 - LISTA 02 - ESTRUTURA DE DECISÃO print('Maior número de dois') print('####################') número1=float(input("Insira um número: ")) número2=float(input("Insira um número: ")) if número1>número2: print('O número: ',número1,' é maior que: ',número2) elif número1==número2: print('O número: ', número1, ' é igual à: ', número2) else: print('O número: ', número2, ' é maior que: ', número1)
# EXERCÍCIO Nº 35- LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nNúmeros Primos') print('##############\n') intervalo=0 while intervalo<=0: intervalo =float(input('\nInsira um número inteiro e >0: ')) while (intervalo) != int(intervalo) or intervalo<=0: print('O número deve ser inteiro e maior que zero') n = float(input('Insira um número inteiro e >0: ')) intervalo=int(intervalo) print('Os números primos até',intervalo,'são os seguintes: ',end='') for n in range(0, intervalo + 1): divisores = 0 for i in range(1, n + 1): if n % i == 0: divisores += 1 if divisores == 2: print(n, end=',') intervalo=0
#EXERCÍCIO Nº 10 - LISTA 02 - ESTRUTURA DE DECISÃO print('Bom dia, Boa tarde e Boa noite') print('##############################') turno=input("Qual turno você estuda? (M/V/N): ") if 'MVN'.find(turno.upper())>=0: if turno.upper()=='M': print('Bom dia!') elif turno.upper()=='V': print('Boa tarde!') else: print('Boa noite!') else: print("Opção inválida")
# EXERCÍCIO Nº 14- LISTA 05 - LISTAS print('\n Quadrado Mágico') print('################\n') import numpy import random matriz = [[1, 2, 3], # i(linha) [4, 5, 6], [7, 8, 9]] resultado=False def quadradoMagico(): global resultado sl = numpy.sum(matriz, axis=1) sc = numpy.sum(matriz, axis=0) sd1 = numpy.diagonal(matriz).sum() sd2 = matriz[0][2] + matriz[1][1] + matriz[2][0] if sl[0]==sl[1]==sl[2]==sc[0]==sc[1]==sc[2]==sd1==sd2: resultado=True else: resultado=False return resultado while resultado==False: seq = [1, 2, 3, 4, 5, 6, 7, 8, 9] for i in range(3): for j in range(3): z = random.choice(seq) matriz[i][j] = z x = seq.index(z) seq = seq[:x] + seq[x + 1:] quadradoMagico() for número in matriz: print(número)
# EXERCÍCIO Nº 34- LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nNúmeros Primos') print('##############\n') n=0 while n<=0: n =float(input('Insira um número inteiro e >0: ')) while (n) != int(n) or n<=0: print('O número deve ser inteiro e maior que zero') n = float(input('Insira um número inteiro e >0: ')) n=int(n) divisores=0 for i in range (1,n+1): if n%i==0: divisores+=1 if divisores ==2: print('O número', n, 'é primo') else: print('O número', n, 'não é primo') n=0
# EXERCÍCIO Nº 32- LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nFatorial de um número inteiro') print('#############################\n') n=0 while n<=0: n =float(input('Insira um número inteiro >0: ')) while (n) != int(n) or n<=0: print('O número deve ser inteiro e maior que zero') n = float(input('Insira um número inteiro >0: ')) n=int(n) fatorial=1 for i in (range(1,n+1)): fatorial *= i print('○ Fatorial de:',n) print('⃝',n,'! = ',end='') for i in reversed(range(2,n+1)): print(i,end=' . ') print('1 =',fatorial)
número01=input('número: ') número02=input('número: ') soma=int(número01)+int(número02) print('A soma dos números é: '+str(soma))
row1 = ["⬜️","⬜️","⬜️"] row2 = ["⬜️","⬜️","⬜️"] row3 = ["⬜️","⬜️","⬜️"] map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") number = list(str(position)) if int(number[1]) == 3: if int(number[0]) == 1: row3[0] = "X" elif int(number[0]) == 2: row3[1] = "X" elif int(number[0]) == 3: row3[2] = "X" elif int(number[1]) == 2: if int(number[0]) == 1: row2[0] = "X" elif int(number[0]) == 2: row2[1] = "X" elif int(number[0]) == 3: row2[2] = "X" elif int(number[1]) == 1: if int(number[0]) == 1: row1[0] = "X" elif int(number[0]) == 2: row1[1] = "X" elif int(number[0]) == 3: row1[2] = "X" else: print("Coordinate is out of range") #second option #horizontal = int(position[0]) #vertical = int(position[1]) #selected_row = map[vertical-1] #selected_row[horizontal - 1] = "X" # print(f"{row1}\n{row2}\n{row3}")
# 1078.Bigram分词 # 给出第一个词first和第二个词second,考虑在某些文本text中可能以"first second third"形式出现的情况,其中second紧随first出现,third紧随second出现。 # 对于每种这样的情况,将第三个词"third"添加到答案中,并返回答案。 # 示例1: # 输入:text = "alice is a good girl she is a good student", first = "a", second = "good" # 输出:["girl", "student"] # 示例2: # 输入:text = "we will we will rock you", first = "we", second = "will" # 输出:["we", "rock"] # 提示: # 1 <= text.length <= 1000 # text由一些用空格分隔的单词组成,每个单词都由小写英文字母组成 # 1 <= first.length, second.length <= 10 # first和second由小写英文字母组成 class Solution: def findOcurrences(self, text: str, first: str, second: str): res = [] array = text.split(" ") if len(array) <= 2: return res for i in range(len(array)-2): if array[i] == first and array[i+1] == second: res.append(array[i+2]) return res sol = Solution() print(sol.findOcurrences("we will we will rock you","we","will"))
# 977. 有序数组的平方 # 给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。 # 示例 1: # 输入:[-4,-1,0,3,10] # 输出:[0,1,9,16,100] # 示例 2: # 输入:[-7,-3,2,3,11] # 输出:[4,9,9,49,121] class Solution: def sortedSquares(self, A): return sorted([i**2 for i in A ]) sol = Solution() print(sol.sortedSquares([-4,-1,0,3,10]))
# 160.相交链表 # 编写一个程序,找到两个单链表相交的起始节点。 # 注意: # 如果两个链表没有交点,返回null. # 在返回结果后,两个链表仍须保持原有的结构。 # 可假定整个链表结构中没有循环。 # 程序尽量满足O(n)时间复杂度,且仅用O(1)内存。 # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): # 方法1:遍历法(超时) def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ i = headA j = headB stack = [] while i : stack.append(i) i = i.next while j : if stack.count(j) == 1: return j.val else: stack.append(j) j = j.next return None # 方法2:双指针遍历相交法 # 创建两个指针 pA 和 pB,分别初始化为链表 A 和 B 的头结点。然后让它们向后逐结点遍历。 # 当pA到达链表的尾部时,将它重定位到链表 B 的头结点 (你没看错,就是链表 B); 类似的, # 当pB到达链表的尾部时,将它重定位到链表 A 的头结点。 # 若在某一时刻 pA 和 pB 相遇,则 pA/pB 为相交结点。 def getIntersectionNode2(self, headA, headB): i = headA j = headB #重定向判断 bool_i = False bool_j = False while i!=None or j!=None: if i != j: if i == None: if bool_i == False: i = headB bool_i = True else: pass else: i = i.next if j == None: if bool_j == False: j = headA bool_j = True else: pass else: j = j.next else: return i.val node1 = ListNode(4) node2 = ListNode(1) node3 = ListNode(5) node4 = ListNode(0) node5 = ListNode(1) node6 = ListNode(8) node7 = ListNode(4) node8 = ListNode(5) node1.next = node2 node2.next = node6 node3.next = node4 node4.next = node5 node5.next = node6 # node6.next = node7 # node7.next = node8 sol = Solution() print(sol.getIntersectionNode2(node1,node3))
#1046. 最后一块石头的重量 #有一堆石头,每块石头的重量都是正整数。 #每一回合,从中选出两块最重的石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下: #如果 x == y,那么两块石头都会被完全粉碎; #如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。 #最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。 #提示: #1 <= stones.length <= 30 #1 <= stones[i] <= 1000 import heapq class Solution: # 方法一,直接使用list的排序方法进行处理 def lastStoneWeight(self, stones): while len(stones) > 1: stones.sort() if stones[len(stones) - 1] == stones[len(stones) - 2]: stones.pop() stones.pop() else: last = stones[len(stones) - 1] - stones[len(stones) - 2] stones.pop() stones.pop() stones.append(last) stones.sort() if len(stones) == 1: return stones[0] else: return 0 # ——————————————————分割线—————————————————— # 该题在解法上使用了推排序的原理,引入了python标准库自带的堆模块heapq # 具体有关该模块的具体方法介绍请看:https://www.jianshu.com/p/801318c77ab5 def lastStoneWeight2(self, stones): heap = [] #对stones进行默认最小堆创建,因此我们存入数据时,将每个数据都乘以-1,则绝对值最大的数就在最小堆的根元素 for i in stones: heapq.heappush(heap,i*(-1)) #记录石头个数 left_stones = len(stones) #当石头个数小于等于一个时,停止循环 while left_stones>1: #弹出heap堆中最小的一个元素,「实为弹出的是最大的元素,因为全部加了负号」 first = heapq.heappop(heap) #,同理,再弹出一个, second = heapq.heappop(heap) #对弹出的这两个数进行比较 if first==second: left_stones = left_stones - 2 else: heapq.heappush(heap,first - second) left_stones = left_stones - 1 #返回结果 #如果剩余一个,则返回那个结果的倒数(因为之前所有数全部都是乘以-1的),若石头相撞完则返回0 if left_stones==1: return heapq.heappop(heap)*(-1) else: return 0 sol = Solution() print(sol.lastStoneWeight([2,3,1])) print(sol.lastStoneWeight2([2,3,1]))
# 429. N叉树的层序遍历 # 给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。 # 例如,给定一个 3叉树 : # 1 # / | \ # 3 2 4 # / \ # 5 6 # 返回其层序遍历: # [ # [1], # [3,2,4], # [5,6] # ] # Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children class Solution: # 非递归解法,和同目录下的二叉树层序遍历题目类似 def levelOrder(self, root: Node): res = [] if not root: return res nodes_list = [root] while nodes_list: nodes = [] cur = [] for node in nodes_list: cur.append(node.val) for child in node.children: nodes.append(child) res.append(cur) nodes_list = nodes return res
#35. 搜索插入位置 # # 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 # # 你可以假设数组中无重复元素。 # # 示例 1: # # 输入: [1,3,5,6], 5 # 输出: 2 # 示例 2: # # 输入: [1,3,5,6], 2 # 输出: 1 # 示例 3: # # 输入: [1,3,5,6], 7 # 输出: 4 # 示例 4: # # 输入: [1,3,5,6], 0 # 输出: 0 def searchInsert(nums,target) -> int: if target<=nums[0]: return 0 elif target>nums[len(nums)-1]: return len(nums) elif target==nums[len(nums)-1]: return len(nums)-1 else: for i in range(1,len(nums)): if nums[i]>=target: return i else: pass print(searchInsert([1,3],3))
# 1122.数组的相对排序 # 给你两个数组,arr1和arr2, # arr2中的元素各不相同 # arr2中的每个元素都出现在arr1中 # 对arr1中的元素进行排序,使arr1中项的相对顺序和arr2中的相对顺序相同。 # 未在arr2中出现过的元素需要按照升序放在arr1的末尾。 # 示例: # 输入:arr1 = [2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19], arr2 = [2, 1, 4, 3, 9, 6] # 输出:[2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19] # 提示: # arr1.length, arr2.length <= 1000 # 0 <= arr1[i], arr2[i] <= 1000 # arr2中的元素arr2[i]各不相同arr2中的每个元素arr2[i]都出现在arr1中 class Solution: def relativeSortArray(self, arr1, arr2): res = [] for i in arr2: while i in arr1: res.append(i) arr1.remove(i) arr1.sort() res = res + arr1 return (res) sol = Solution() print(sol.relativeSortArray([2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19],[2, 4, 3, 9, 6]))
# 54. 螺旋矩阵 # 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 # 示例 1: # 输入: # [ # [ 1, 2, 3 ], # [ 4, 5, 6 ], # [ 7, 8, 9 ] # ] # 输出: [1,2,3,6,9,8,7,4,5] # 示例 2: # 输入: # [ # [1, 2, 3, 4], # [5, 6, 7, 8], # [9,10,11,12] # ] # 输出: [1,2,3,4,8,12,11,10,9,5,6,7] class Solution: def spiralOrder(self, matrix): if not matrix: return [] up_row = 0 down_row = len(matrix) - 1 left_col = 0 right_col = len(matrix[0]) - 1 res = [] while up_row <= down_row and left_col <= right_col: # 从左到右 for i in range(left_col, right_col + 1): res.append(matrix[up_row][i]) up_row += 1 if up_row > down_row: break # 从上到下 for i in range(up_row, down_row + 1): res.append(matrix[i][right_col]) right_col -= 1 if left_col > right_col: break # 从右到左 for i in range(right_col, left_col - 1, -1): res.append(matrix[down_row][i]) down_row -= 1 # 从下到上 for i in range(down_row, up_row - 1, -1): res.append(matrix[i][left_col]) left_col += 1 return res sol = Solution() print(sol.spiralOrder([[1, 2, 3, 4],[5, 6, 7, 8],[9,10,11,12]]))
# 206. 反转链表 # 反转一个单链表。 # 示例: # 输入: 1->2->3->4->5->NULL # 输出: 5->4->3->2->1->NULL # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 我的做法:使用了一个堆栈用来存储链表中的每个节点 def reverseList(self, head: ListNode) -> ListNode: # 创建一个堆栈 node_stack = [] node = head # 将每个节点保存在堆栈中 while node != None: node_stack.append(node) node = node.next # 创建一个头节点 root = ListNode(-1) i = root # 循环将每个节点弹出堆栈 while node_stack: # 取出后进堆栈的节点 node = node_stack.pop() # 改变他们的next属性 i.next = node i = i.next i.next = None return root.next # 评论中的高赞答案:详细解析见:https://blog.csdn.net/xyh269/article/details/70238501 # 此方法使用了三个指针,进行联动遍历 def reverseList2(self,head:ListNode) -> ListNode: pre = None cur = head while cur != None: n = cur.next cur.next = pre pre = cur cur = n return pre node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 sol = Solution() print(sol.reverseList2(node1))
# 1089.复写零 # 给你一个长度固定的整数数组arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。 # 注意:请不要在超过该数组长度的位置写入元素。 # 要求:请对输入的数组就地进行上述修改,不要从函数返回任何东西。 # 示例1: # 输入:[1, 0, 2, 3, 0, 4, 5, 0] # 输出:null # 解释:调用函数后,输入的数组将被修改为:[1, 0, 0, 2, 3, 0, 0, 4] # 示例2: # 输入:[1, 2, 3] # 输出:null # 解释:调用函数后,输入的数组将被修改为:[1, 2, 3] # 提示: # 1 <= arr.length <= 10000 # 0 <= arr[i] <= 9 class Solution: def duplicateZeros(self, arr) -> None: """ Do not return anything, modify arr in-place instead. """ l = len(arr) i = 0 while i<l-1: if arr[i] == 0: arr.pop() arr.insert(i,0) i = i + 2 else: i = i + 1 sol = Solution() print(sol.duplicateZeros([1, 0, 2, 3, 0, 4, 5, 0]))
# 970.强整数 # 给定两个正整数x和y,如果某一整数等于x ^ i + y ^ j,其中整数i >= 0且j >= 0,那么我们认为该整数是一个强整数。 # 返回值小于或等于bound的所有强整数组成的列表。 # 你可以按任何顺序返回答案。在你的回答中,每个值最多出现一次。 # 示例1: # 输入:x = 2, y = 3, bound = 10 # 输出:[2, 3, 4, 5, 7, 9, 10] # 解释: # 2 = 2 ^ 0 + 3 ^ 0 # 3 = 2 ^ 1 + 3 ^ 0 # 4 = 2 ^ 0 + 3 ^ 1 # 5 = 2 ^ 1 + 3 ^ 1 # 7 = 2 ^ 2 + 3 ^ 1 # 9 = 2 ^ 3 + 3 ^ 0 # 10 = 2 ^ 0 + 3 ^ 2 # 示例2: # 输入:x = 3, y = 5, bound = 15 # 输出:[2, 4, 6, 8, 10, 14] # 提示: # 1 <= x <= 100 # 1 <= y <= 100 # 0 <= bound <= 10 ^ 6 class Solution: def powerfulIntegers(self, x: int, y: int, bound: int): if x == y == 1: if bound >= 2: return [2] else: return [] elif x>1 and y==1: res = [] i = 0 flag = True while flag: cur = x**i + 1 if cur <= bound: res.append(cur) i = i + 1 else: flag = False return sorted(set(res)) elif x==1 and y>1: res = [] i = 0 flag = True while flag: cur = 1 + y**i if cur <= bound: res.append(cur) i = i + 1 else: flag = False return sorted(set(res)) else: res = [] flagI = True i = 0 while flagI: j = 0 flagJ = True if x**i + y**j <= bound: while flagJ: cur = x**i + y**j if cur <= bound: res.append(cur) j = j + 1 else: flagJ = False i = i + 1 else: flagI = False return sorted(set(res)) sol = Solution() print(sol.powerfulIntegers(1,2,2))
# Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. def func_var3(x): x = str(x) y = x[::-1] return y #100 loops, best of 5: 404 nsec per loop - Трехзначное число #100 loops, best of 5: 423 nsec per loop - Шестизначное число #100 loops, best of 5: 457 nsec per loop - Десятизначное число #100 loops, best of 5: 619 nsec per loop - Двадцатизначное число # Линейный алгоритм, сложность алгоритма возрастает пропорционально количеству цифр в числе. # Судя по полученным данным по времени работы алгоритма (измерению и функции зависимости разрядности числа от времени работы), данный алгоритм является самым быстродейственным для решения задачи.
#1. Пользователь вводит данные о количестве предприятий, их наименования и прибыль за 4 квартала (т.е. 4 отдельных числа) для каждого предприятия.. Программа должна определить среднюю прибыль (за год для всех предприятий) и вывести наименования предприятий, чья прибыль выше среднего и отдельно вывести наименования предприятий, чья прибыль ниже среднего. from collections import namedtuple Enterprise = namedtuple("Enterprise", "name profit_1q profit_2q profit_3q profit_4q") def read_ent(): name = input("Введите название предприятия ") p1 = int(input("Введите прибыль предприятия за первый квартал ")) p2 = int(input("Введите прибыль предприятия за второй квартал ")) p3 = int(input("Введите прибыль предприятия за третий квартал ")) p4 = int(input("Введите прибыль предприятия за четвертый квартал ")) ent = Enterprise(name, p1, p2, p3, p4) return ent def mid_profit_one(lst_ent): mid_ent = [((ent.profit_1q + ent.profit_2q + ent.profit_3q + ent.profit_4q)) for i, ent in enumerate(lst_ent)] return mid_ent def mid_profit_all(mid_p, num_ent): summ = 0 for p in mid_p: summ = summ + p midle = summ/num_ent return midle def main(): num_ent = int(input("Введиите количество предприятий ")) lst_ent = [read_ent() for i in range(num_ent)] mid_p = mid_profit_one(lst_ent) mid_all = mid_profit_all(mid_p, num_ent) print(f"Средняя прибыль по всем предприятиям: {mid_all}") lst_ent_small = [] lst_ent_big = [] for i, p in enumerate(mid_p): if p < mid_all: lst_ent_small.append(lst_ent[i]) elif p > mid_all: lst_ent_big.append(lst_ent[i]) else: continue print("Предприятия, у которых прибыль больше средней") for ent in lst_ent_big: print(ent.name) print("Предприятия, у которых прибыль меньше средней") for ent in lst_ent_small: print(ent.name) main()
# 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. import random size = 10 max_item = 10 array = [random.randint(0, max_item) for i in range(size)] min_el = max_item max_el = 0 max_index = 0 min_index = 0 for index, value in enumerate(array): if value > max_el: max_el = value max_index = index if value < min_el: min_el = value min_index = index i = min_index + 1 summ = 0 while i < max_index: summ += array[i] i += 1 print(f"Исходный массив: {array}") print(f"Сумма элементов между максимальным и минимальным элементами: {summ}")
# 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. x = int(input("Введите число ")) n = x count = 0 z = 0 while n > 0: n = n // 10 count += 1 while count > 0: a = x % 10 y = a * 10 ** (count - 1) z += y x = x // 10 count -= 1 print(f"Обратное число {z}")
# 백준, 2941번 크로아티아 알파벳 word = input() alpha = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="] for c_a in alpha : if c_a in word : word = word.replace(c_a, "A") print(len(word))
# Task # The provided code stub reads two integers, a and b, from STDIN. # Add logic to print two lines. The first line should contain the result of integer division, a // b. # The second line should contain the result of float division, a / b. # No rounding or formatting is necessary. # Input format: # The first line contains the first integer, a. # The second line contains the second integer, b. # Output format: # Print the two lines as described above. # CODE from __future__ import division if __name__ == '__main__': a = int(raw_input()) b = int(raw_input()) div1 = a//b div2 = a/b print (div1) print (div2)
import pygame from time import sleep import socket, struct pygame.init() #Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # Initialize the joysticks pygame.joystick.init() # -------- Main Program Loop ----------- while done==False: # EVENT PROCESSING STEP for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done=True # Flag that we are done so we exit this loop # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION if event.type == pygame.JOYBUTTONDOWN: print("Joystick button pressed.") if event.type == pygame.JOYBUTTONUP: print("Joystick button released.") # Get count of joysticks joystick_count = pygame.joystick.get_count() #print("Number of joysticks: {}".format(joystick_count) ) # For each joystick: x=0 for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) joystick.init() # print("Joystick {}".format(i) ) # Get the name from the OS for the controller/joystick name = joystick.get_name() # print("Joystick name: {}".format(name) ) # Usually axis run in pairs, up/down for one, and left/right for # the other. axes = joystick.get_numaxes() #print("Number of axes: {}".format(axes) ) for i in range( axes ): axis = joystick.get_axis( i ) #print("Axis {} value: {:>6.3f}".format(i, axis) ) buttons = joystick.get_numbuttons() # print( "Number of buttons: {}".format(buttons) ) for i in range( buttons ): button = joystick.get_button( i ) #print("Button {:>2} value: {}".format(i,button) ) # Hat switch. All or nothing for direction, not like joysticks. # Value comes back in an array. hats = joystick.get_numhats() #print("Number of hats: {}".format(hats) ) for i in range( hats ): hat = joystick.get_hat( i ) # print("Hat {} value: {}".format(i, str(hat)) ) #sleep(.1) button6= joystick.get_button(6) button7= joystick.get_button(7) track=0 if button6 == 1: track = -1 if button7 == 1: track = 1 track = track * 127.5 track = track + 127.5 axis0 = joystick.get_axis( 0 ) axis1 = joystick.get_axis( 1 ) axis2 = joystick.get_axis( 2 ) axis3 = joystick.get_axis( 3 ) if .10 > axis0 > -.10: axis0=0 if .10 > axis1 > -.10: axis1=0 if .10 > axis2 > -.10: axis2=0 if .10 > axis3 > -.10: axis3=0 axis0=axis0*127.5 #makes the range (-127.5,127.5) axis0=axis0+127.5 #Shifts the center to 127.5. Our range is now (0,255) axis1=axis1*127.5 axis1=axis1+127.5 axis2=axis2*127.5 axis2=axis2+127.5 axis3=axis3*127.5 axis3=axis3+127.5 test = axis0+axis1+axis2+axis3+track #print test s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('192.168.1.42', 5050)) #('Ip address', port) we're using port 5050 it could be any port really but I chose this one packer = struct.Struct('B B B B B') data = packer.pack(axis2,axis3,axis0,axis1,track) #stores the values of axis2 into the first bit, and axis3 in the second bit if test != 637.5: s.send(data) sleep(.1) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT # Go ahead and update the screen with what we've drawn. # Limit to 20 frames per second clock.tick(20) # Close the window and quit. # If you forget this line, the program will 'hang' # on exit if running from IDLE. pygame.quit ()
#!/usr/bin/python3 import numpy as np import sympy as sym from sympy.physics.mechanics import dynamicsymbols class BaseSymbols: def __init__(self, name, identifier, is_coords=False): """The base object for this whole package to function. It defines the sympy symbols that are used in the modelling process, whether it be translational (x,y,z), rotational (theta_x, theta_y, theta_z) coordinates, positions within a reference frame, or the direction and magnitude of forces and torques, all the symbols are generated by various combinations of this object. Later, we have specific object thats handle these scenarios for us, but all inherit from this class. s such, we never explicility use this class Args: name (int or str): the name for the symbols. This will form the superscript, i.e., the body the symbols refer to. identifier (int or str): gives meaning to the symbol set as it identifies what or where the symbol set refer to. For a set of coordinates, this is "G", the centre of mass. For a force, torque or length it is F, tau and l respectively. is_coords (int or str): defines if a sextuple is defines (representing the 6 coordinates) of a body, or a triple (representing the three Cartesian coordinates). Example: A coordinate representation of body named "1", at its centre of mass, G. >>> from skydy.configuration import BaseSymbols >>> body_name = "1" >>> body_loc = "G" >>> body_symbols = BaseSymbols(body_name, body_loc, True) A vector representation of force named "2" >>> force_name = "2" >>> force_id = "F" >>> force_symbols = BaseSymbols(force_name, force_id) A vector representation of distance, or dimension for a body named "1" >>> dim_name = "1" >>> dim_id = "l" >>> dim_symbols = BaseSymbols(dim_name, dim_id) """ self.name = name self.__is_coords = is_coords if is_coords: axes = ["x", "y", "z"] trans_symbols = ["{}^{}_{}".format(ax, name, identifier) for ax in axes] rot_symbols = ["theta^{}_{}".format(name, ax) for ax in axes] all_symbols = trans_symbols + rot_symbols self.__symbols = sym.Matrix([dynamicsymbols(var) for var in all_symbols]) else: axes = ["x", "y", "z"] self.__symbols = sym.Matrix( [sym.Symbol("{}^{}_{}".format(identifier, name, ax)) for ax in axes] ) self.__values = np.ones(self.__symbols.shape) def symbols(self): """Get the sympy.matrices.dense.MutableDenseMatrix of the symbols.""" if self.__is_coords: return self.__symbols else: sym_dict = self.as_dict() # only return the symbol if the value is non-zero. return sym.Matrix([k if v else 0 for k, v in sym_dict.items()]) def values(self): """Return a numpy.ndarray of the values. If the values are not assigned, they return an array of ones by default.""" return self.__values def as_dict(self): """Get the dictionary of symbol-value pairs.""" return {s: v.item() for s, v in zip(self.__symbols, self.__values)} def assign_values(self, values, idx=-1): """Assign value(s) to a symbol. By defualt, the value is instantiated as 1. Args: values (array-like object, int or float): the values we want to assign. This must be an array-like object of the len(self.__symbols), or an integer. If an integer is provided, a valid index must be provided. idx (int): for an int or float, the index to assign the value to. This must be a valid index in 0 to len(self.__symbols)-1. Returns: None Example: >>> from skydy.configuration import BaseSymbols >>> base_symbols = BaseSymbols("1", "G") >>> # Assign all values >>> base_symbols.assign_values([10, 20, 30, 40, 50, 60]) >>> # Assign just one value >>> base_symbols.assign_values(24, 4) """ if isinstance(values, str): raise TypeError("Values must be an integer, float or boolean.") elif hasattr(values, "__len__"): if len(values) == len(self.__values): self.__values = np.array(values).reshape(-1, 1) else: raise ValueError("Values must be same dimension as value object.") elif ( isinstance(values, int) or isinstance(values, float) or isinstance(values, bool) ): if 0 <= idx < len(self.__values): self.__values[idx, 0] = values else: raise ValueError( "Index must be in the range 0 to {}".format(len(self.__values)) ) else: raise TypeError( "Values must be an array like object with {} entries, or a value with an appropriate index between 0 and {}".format( len(self.__values), len(self.__values) - 1 ) ) def sym_to_np(self, sym_matrix): """Convert a numeric sympy matrix, i.e., after substituting values, to a numpy matrix. We pass in the sympy matrix for flexbility down the line as to what we can and cannot convert. Args: sym_matrix (sympy.matrices.dense.MutableDenseMatrix): a sympy matrix, with values substituted in. Returns: np_matrix (numpy.ndarray): a numpy matrix of same dimensions of the input matrix. Example: >>> from skydy.configuration import BaseSymbols >>> base_symbols = BaseSymbols("1", "G") >>> # Assign all values >>> base_symbols.assign_values([10, 20, 30, 40, 50, 60]) >>> # Crete a matrix of symbols >>> sym_mat = base_symbols.symbols() >>> # Substitute the values in >>> sym_mat = sym_mat.subs(base_symbols.as_dict()) >>> # Convert to an numpy.ndarray. >>> np_mat = base_symbols.sym_to_np(sym_mat) """ return np.array(sym_matrix.tolist()).astype(float) class CoordinateSymbols(BaseSymbols): def __init__(self, name): """A set of coordinate symbols, inheriting from the BaseSymbols class. Coordinate symbols are simply the translational (x,y,z) and rotational (theta_x, theta_y, theta_z) coordinates about the centre of mass of a body. As expected, use the RIGHT HAND RULE to determine coordinate directions. Fix your x-axis appropriately, and the rest comes for free. Args: name (int, float or string): the name of the body or object we want to generate coordinates for. Returns: None Example: >>> from skydy.configuration import CoordinateSymbols >>> # Create a set of symbols >>> body_name = 1 >>> body_coords = CoordinateSymbols(body_name) """ super().__init__(name, "G", True) def positions(self): """Returns the symbols of the positions (or coordinates) of the body.""" return self.symbols() def velocities(self): """Returns the velocities of the positions (or coordinates) of the body.""" return sym.Matrix([sym.diff(var, sym.Symbol("t")) for var in self.symbols()]) class DimensionSymbols(BaseSymbols): def __init__(self, name): """A set of dimension symbols, inheriting from the BaseSymbols class. Dimension symbols simply exist in x-, y-, z-coordinates. By default, these symbols are defined by l, or a length. Args: name (int, float or string): the name of the body or object we want to generate dimensions for. Returns: None Example: >>> from skydy.configuration import DimensionSymbols >>> # Create a set of symbols >>> body_name = 1 >>> body_dims = DimensionSymbols(body_name) """ super().__init__(name, "l", False) class ForceSymbols(BaseSymbols): def __init__(self, name): """A set of force symbols, inheriting from the BaseSymbols class. Force symbols simply exist in x-, y-, z-coordinates. By default, these symbols are defined by F, or a Force. Args: name (int, float or string): the name of the body or object we want to designate a force for. Returns: None Example: >>> from skydy.configuration import ForceSymbols >>> # Create a set of symbols >>> body_name = 1 >>> body_forces = ForceSymbols(body_name) """ super().__init__(name, "F", False) class TorqueSymbols(BaseSymbols): def __init__(self, name): """A set of torque symbols, inheriting from the BaseSymbols class. Torque symbols simply exist as rotations about the x-, y-, z-coordinates. By default, these symbols are defined by tau, or a Torque. Args: name (int, float or string): the name of the body or object we want to designate a Torque for. Returns: None Example: >>> from skydy.configuration import TorqueSymbols >>> # Create a set of symbols >>> body_name = 1 >>> body_torques = TorqueSymbols(body_name) """ super().__init__(name, "tau", False)
#!/usr/bin/python3 class DOF: def __init__(self, idx, free=True, const_value=0): """A Degree of Freedom is nothing other than a body coordinate that is able to move. Thus, to define a DOF, we need to simply supply the free index (idx). By default, if it is free, there is no constant value, so we do not need to supply the second, or third arguments. Args: idx (int): the free coordinate index, between 0 and 5. free (bool): if the coordinte at index idx is free. True by default. const_value (int or float): If the DOF is not free, i.e., free=False on instantiation, we assign the constant value the coordinate has. By defualt this is zero. Returns: None Example: Demonstrate all combinations of the DOF construction. >>> from skydy.connectors import DOF >>> # Define a DOF in the x-coordinate >>> x_dof = DOF(0) >>> # Note the following ALSO defines a coordinate in the y-direction >>> y_dof = DOF(1, True) >>> # Define a constraint in the z-direction, at a value of 10. >>> z_con = DOF(1, False, 10) >>> # Define a constraint in the theta_z-direction, at a value of 2. >>> theta_z_con = DOF(5, False, 2) """ self.idx = idx self.free = free self.const_value = const_value @property def idx(self): return self._idx @idx.setter def idx(self, val): if 0 <= val <= 5: self._idx = val else: raise ValueError("idx must be between 0 and 5.") @property def free(self): return self._free @free.setter def free(self, val): if isinstance(val, bool): self._free = val else: raise TypeError("free must be boolean value.") @property def const_value(self): return self._const_value @const_value.setter def const_value(self, val): if isinstance(val, int) or isinstance(val, float): if self.free: self._const_value = 0 else: self._const_value = val else: raise TypeError("const_value attribute must be boolean value.")
"""金典排序之冒泡法""" def bubble_sort(alist): for j in range(len(alist) - 1,0,-1): # j 表示每次遍历需要比较的次数,是逐渐减小的 for i in range(j): if alist[i] > alist[i+1]: alist[i],alist[i+1] = alist[i+1],alist[i] li = [32,23,22,33,34,45,65,39] bubble_sort(li) print(li)
# squares = [i **0.5 for i in range(1,11)] # print(squares) # a = [ i for i in range(1,1000001)] # print(max(a)) # print(min(a)) # print(sum(a)) # # # a = [i for i in range(1,20,2)] # print(a) # # a = [i*3 for i in range(1,10)] # # print(a) # # # b = [i**3 for i in range(1,11)] # #if len(b)<=2: # print("The first three items in the list are:") # for i in b[-3:]: # print(i) # # # print(b) # for i in range(len(b)-3,len(b)): # # print(b[i]) # # # # my_food = ['pizza','falafel','carrot cake'] # li_food = my_food[:] # li_food.append('a_pazza') # print('lifood:',li_food) # print('myfood:',my_food) # # print("my favorite pizzas are: ") # for i in my_food: # print(i) # # print("li favorite pizzas are:") # # for i in li_food: # print(i) # # # dimensions = (200,50) # # print(dimensions[0]) # # print(dimensions[1]) # print("~~~~~~~~~~~~~~") # for dimension in dimensions: # print(dimension) # # # dimensions = (200,50) # print("Orginal dimensions: ") # for dimension in dimensions: # print(dimension) # dimensions = (400,100) # print("Modidied dimensions: ") # for dimension in dimensions: # print(dimension) # frults = ('apple', 'pear', 'banana', 'grope', 'peach') # print('The frults are: ') # for frult in frults: # print(frult) # requested_toppings = ['mushrooms','green peppers','extra cheese'] # # for requested_topping in requested_toppings: # print("Adding "+ requested_topping + ".") # # print("\nFinished mading your pizza!") # # alien_0 = {'color': 'green', 'points': 5} # print(alien_0['color']) # print(alien_0['points']) # # new_points = alien_0['points'] # print("You just earned " + str(new_points) + " points!") # # del alien_0['points'] # print(alien_0) # # dict = { # 'a':'123', # 'b':'456' # # } # # for k,v in dict.items(): # print(v) # # # for k,v in enumerate(dict): # print(dict[v]) # # for key in dict: # print(key) # # for value in dict.values(): # print(value) # # favorite_languages = { # 'jen':'python', # 'sarch':'c', # 'edward':'ruby', # 'phil':'python', # } # # for name in sorted(favorite_languages.keys()): # print(name.title() + ", thank you for taking the poll.") # # for language in set(favorite_languages.values()): # print(language) # # aliens = [] # for alien_number in range(30): # new_aliens = {'color':'green','points':5,'speed':'slow'} # aliens.append(new_aliens) # # for alien in aliens[:5]: # print(alien) # print('...') # x = 1 # while x < 10: # # x +=1 # print(x) responses = {} polling_active = True while polling_active: name = input("\nWhat is your name?") response = input("Which mountain would you like to climb someday? ") responses[name] = response repeat = input("Would you like to let another person respond? (yes/ no) ") if repeat == 'no': polling_active = False print("\n --- Poll Results --- ") for name,response in responses.items(): print(name + " would like to climb " + response + ".") print(responses)
import math mylist = [] answers = [] def answer(area): curArea = area; i = 0 while curArea > 0: getSqrt(curArea) curArea = curArea - mylist[i]; i = i+1; answers = list(mylist) del mylist[:] return answers; def getSqrt(area): floorRoot = int(math.sqrt(area)) mylist.append(floorRoot * floorRoot) return;
#!/usr/bin/python3 """ Script to export data in the CSV format """ import csv import requests from sys import argv def export_to_csv(employee_id): """ Retrieves the ToDo list for an employee in CSV """ url = 'https://jsonplaceholder.typicode.com/' user_request = '{}users/{}'.format(url, employee_id) employee_dict = requests.get(user_request).json() employee_name = employee_dict.get('username') tasks_dict = requests.get('{}todos?userId={}' .format(url, employee_id)).json() file_name = '{}.csv'.format(employee_id) with open(file_name, mode='w') as csv_file: csv_writer = csv.writer(csv_file, quoting=csv.QUOTE_ALL) for element in tasks_dict: csv_writer.writerow([employee_id, employee_name, element['completed'], element['title']]) if __name__ == "__main__": export_to_csv(argv[1])
# Jacob Wahl # 3/2/21 # # Problem 2.6 - Implement a function to check if a linked list is a # palindrome. # from Linked_List import Linked_List, Node def is_palindrome_helper(llist: Linked_List): fowards, backwards = is_palindrome(llist.head, '', '') print(fowards, backwards) return True if fowards.replace(' ', '') == backwards.replace(' ', '') else False def is_palindrome(node: Node, fowards: str, backwards: str) -> tuple: if node == None: return fowards, backwards else: fowards += node.val fowards, backwards = is_palindrome(node.next, fowards, backwards) backwards += node.val return fowards, backwards def string_to_list(li: list) -> list: ret_list = [] for i in li: llist = Linked_List() for cur in i: llist.append(cur) ret_list.append(llist) return ret_list test_cases = ['', 'a', 'aba', 'abcba', 'acda', 'taco cat'] test_cases = string_to_list(test_cases) print(test_cases) test_cases = string_to_list(test_cases) for i in test_cases: print(is_palindrome_helper(i))
# Jacob Wahl # 4/6/21 # # Problem 8.3 - A magic index in an array A[0 ... n-1] is defined to be an # index such that A[i] = i. Given a sorted array of distinct, # write a method to find a magic index, if one exists, in array # A. # FOLLOW UP: What if the values are not distinct? def find_magic_idnex(A): return find_magic_index_recurse_follow_up(A, 0, len(A)-1) ''' def find_magic_index_recurse(A, start, stop): if start > stop: return False middle = (stop - start // 2) + start if A[middle] == middle: return middle elif A[middle] < middle: return find_magic_index_recurse(A, middle+1, stop) else: return find_magic_index_recurse(A, start, middle-1) ''' def find_magic_index_recurse_follow_up(A, start, stop): if start > stop: return -1 middle = (stop - start // 2) + start if A[middle] == middle: return middle rightIdx = min(A[middle], middle-1) result = find_magic_index_recurse_follow_up(A, start, rightIdx) if result != -1: return result leftIdx = max(middle+1, A[middle]) result = find_magic_index_recurse_follow_up(A, leftIdx, stop) return result ''' test_cases = [[0, 4, 7, 9, 10], [-1, 1, 11, 22, 33], [-2, 0, 2, 23, 45], [-22, -9, -10, 3, 20], [-6, -3, 0, 2, 4], [-1, 0, 0, 0, 0], [55, 60, 75, 78, 99]] ''' test_cases = [-10, -5, 2, 2, 2, 3, 4, 8, 9, 12, 13] print(find_magic_idnex(test_cases))
# Jacob Wahl # 2/4/21 # Problem 1.7 - Given an image represnted by an NxN matrix, where each pixel in the image is 4 bytes, # write a method to rotate the image by 90 degrees. Can you do this in place? # Using ints instead of 4 bytes because the method should be the same in essence # Assuming clockwise rotaion def rotateImage(matrix): N = len(matrix) # Not in place ''' new_matrix = [[0 for x in range(N)] for x in range(N)] i = 0 while i < N: j = 0 while j < N: new_matrix[j][(N-1) - i] = matrix[i][j] j += 1 i += 1 return new_matrix ''' # In place if N % 2 == 0: for Sr in range(0, N//2 - 1): Sc = Sr Fc = N - 2 - Sc length = Fc - Sc + 1 Top = (Sr, Sc) Right = (Sr, Fc + 1) Bot = (N - 1 - Sr, Fc + 1) Left = (N - 1 - Sr, Sc) for i in range(length): tmp = matrix[Top[0]][Top[1] + i] matrix[Top[0]][Top[1] + i] = matrix[Left[0] - i][Left[1]] matrix[Left[0] - i][Left[1]] = matrix[Bot[0]][Bot[1] - i] matrix[Bot[0]][Bot[1] - i] = matrix[Right[0] + i][Right[1]] matrix[Right[0] + i][Right[1]] = tmp tmp = matrix[N//2 - 1][N//2 - 1] matrix[N//2 - 1][N//2 - 1] = matrix[N//2][N//2 - 1] matrix[N//2][N//2 - 1] = matrix[N//2][N//2] matrix[N//2][N//2] = matrix[N//2 - 1][N//2] matrix[N//2 - 1][N//2] = tmp else: for Sr in range(0, max(1, N//2 - 1)): Sc = Sr Fc = N - 2 - Sc length = Fc - Sc + 1 Top = (Sr, Sc) Right = (Sr, Fc + 1) Bot = (N - 1 - Sr, Fc + 1) Left = (N - 1 - Sr, Sc) for i in range(length): tmp = matrix[Top[0]][Top[1] + i] matrix[Top[0]][Top[1] + i] = matrix[Left[0] - i][Left[1]] matrix[Left[0] - i][Left[1]] = matrix[Bot[0]][Bot[1] - i] matrix[Bot[0]][Bot[1] - i] = matrix[Right[0] + i][Right[1]] matrix[Right[0] + i][Right[1]] = tmp return matrix test_case = [['h', 'd', 'a'], ['i', 'e', 'b'], ['j', 'f', 'c']] z = 0 while z < 4: test_case = rotateImage(test_case) for i in test_case: print(i) print() z += 1
# Petit exercice utilisant la bibliothèque graphique tkinter from tkinter import * from random import randrange # --- définition des fonctions gestionnaires d'événements : --- def drawline(): "Tracé d'une ligne dans le canevas can1" global x1, y1, x2, y2, coul can1.create_line(x1,y1,x2,y2,width=2,fill=coul) # modification des coordonnées pour la ligne suivante : y2, y1 = y2+10, y1-10 def changecolor(): "Changement aléatoire de la couleur du tracé" global coul pal = ['purple', 'cyan', 'maroon', 'green', 'red', 'blue', 'orange', 'yellow'] c = randrange(8) # => génère un nombre aléatoire de 0 à 7 coul = pal[c] # ------ Programme principal ------- # les variables suivantes seront utilisées de manière globale : x1, y1, x2, y2 = 10, 190, 190, 10 # coordonnées de la ligne coul = 'dark green' # couleur de la ligne # Création du widget principal ("maître") : fen1 = Tk() # création des widgets "esclaves" : can1 = Canvas(fen1, bg='dark grey', height=200, width=200) can1.pack(side=LEFT) bou1 = Button(fen1, text='Quitter', command=fen1.quit) bou1.pack(side=BOTTOM) bou2 = Button(fen1, text='Tracer une ligne', command=drawline) bou2.pack() bou3 = Button(fen1, text='Autre couleur', command=changecolor) bou3.pack() fen1.mainloop() # démarrage du réceptionnaire d’événements fen1.destroy() # destruction (fermeture) de la fenêtre
class Personne: "Classe personne" def __init__(self, nom, prenom): self._nom = nom self._prenom = prenom def __str__(self): return 'Mon prenom est {} et mon nom est {}'.format(self._prenom, self._nom) class Espion(Personne): "Espion" def __init__(self, nom, prenom, nomCode): Personne.__init__(self,nom, prenom) self._nomCode = nomCode def getNom(self): return self._nom def setNom(self, nom): self._nom = nom def __str__(self): return 'Mon prenom est {} et mon nom est {}, code {}'.format(self._prenom, self._nom, self._nomCode) e = Espion("Bond", "James","007") print(e) print(e.getNom()) e.setNom('Bonde') print(e)
liste = [1,6,9,4,5,7] plusFort = 0 for nb in liste: if nb>plusFort: plusFort = nb print("Le plus fort de la liste est {}".format(plusFort))
from abc import ABC, abstractmethod class Forme(ABC): @abstractmethod def aire(self): pass @abstractmethod def perimetre(self): pass class carre(Forme): def __init__(self, largeur,longueur): self._largeur = largeur self._longueur = longueur def aire(self): return self._longueur*self._largeur def perimetre(self): return 2*(self._longueur) + 2*(self._largeur) c = carre(10,10) print(c.aire())
figure = input() area = 0 import math if figure == "square": a = float(input()) area = a * a elif figure == "rectangle": a = float(input()) b = float(input()) area = a * b elif figure == "circle": r = float(input()) area = math.pi * r * r elif figure == "triangle": a = float(input()) h = float(input()) area = a * h / 2 print(str(format(round(area, 3))))
n = int(input()) odd_sum = 0 odd_min = 1000000000000 odd_max = -1000000000000 even_sum = 0 even_min = 10000000000000 even_max = -10000000000000 for i in range(0, n): num = float(input()) if i % 2 == 0: odd_sum += num if num >= odd_max: odd_max = num if num <= odd_min: odd_min = num else: even_sum+= num if num >= even_max: even_max = num if num <= even_min: even_min = num if even_min ==10000000000000: even_min = "No" if even_max == -10000000000000: even_max = "No" if odd_min == 1000000000000: odd_min = "No" if odd_max == -1000000000000: odd_max = "No" if odd_sum % 1 != 0 and (n != 0 or n != 1): print(f"OddSum={odd_sum},") else: print(f"OddSum={int(odd_sum)},") if odd_min % 1 != 0 and (n != 0 or n != 1): print(f"OddMin={odd_min},") else: print(f"OddMin={int(odd_min)},") if odd_max % 1 != 0 and (n != 0 or n != 1): print(f"OddMax={odd_max},") else: print(f"OddMax={int(odd_max)},") if even_sum % 1 != 0 and (n != 0 or n != 1): print(f"EvenSum={even_sum},") else: print(f"EvenSum={int(even_sum)},") if even_min % 1 != 0 and (n != 0 or n != 1): print(f"EvenMin={even_min},") else: print(f"EvenMin={int(even_min)},") if even_max % 1 != 0 and (n != 0 or n != 1): print(f"EvenMax={even_max},") else: print(f"EvenMax={int(even_max)},")
n = int(input()) max_number = 0 sum = 0 for i in range (0, n): num = int(input()) sum += num if num >= max_number: max_number = num if max_number == sum - max_number: print("Yes") print("Sum = " + str(max_number)) else: print("No") print("Diff = " + str(abs(max_number - (sum - max_number))))
# name = input("Enter your name") # print(type(name), name) # num9 = int(name) # print(type(num), num) thisDicto = { "name": "Praneet", "marks": 80 } print(thisDicto["marks"])
## How to create a Set # set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) ## How to Update Set # initialize my_set my_set = {1,3} print(my_set) # if you uncomment line 9, # you will get an error # TypeError: 'set' object does not support indexing #my_set[0] # add an element # Output: {1, 2, 3} my_set.add(2) print(my_set) # add multiple elements # Output: {1, 2, 3, 4} my_set.update([2,3,4]) print(my_set) # add list and set # Output: {1, 2, 3, 4, 5, 6, 8} my_set.update([4,5], {1,6,8}) print(my_set) ## How to remove element from set # initialize my_set my_set = {1, 3, 4, 5, 6} print(my_set) # discard an element # Output: {1, 3, 5, 6} my_set.discard(4) print(my_set) # remove an element # Output: {1, 3, 5} my_set.remove(6) print(my_set) # discard an element # not present in my_set # Output: {1, 3, 5} my_set.discard(2) print(my_set) # remove an element # not present in my_set # If you uncomment line 27, # you will get an error. # Output: KeyError: 2 #my_set.remove(2) ## Python Set Operations # UNION Operation # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use | operator # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B) # initialize A and B # INTERSECTION Operation A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use & operator # Output: {4, 5} print(A & B) # initialize A and B # SET DIFFERENCE A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use - operator on A # Output: {1, 2, 3} print(A - B) # initialize A and B # SET SYMMERTRIC DIFFERENCE A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use ^ operator or use symmetric_difference() # Output: {1, 2, 3, 6, 7, 8} print(A ^ B)
#should return list of data from a text file def populate_data_from_file(data, file): try: for x in file: data.append(x.rstrip()) return data except TypeError: print({f'Cannnot use .append() or rstrip() if {file} is not a file with text'}) #splits a string into a list, this is useful for working with string from a file def split_file_string(new_list, data): try: for x in data: c = x.split() new_list.append(c) return new_list except TypeError: print({f'Cannnot use .split() on values within {data} if not a string'}) #further separates a list by commas def split_file_list(new_list, data): try: for x in data: new_list.append(x[0].split(",")) return new_list except TypeError: print({f'Cannnot use .append() on values within {data} if not a list'}) #prints exception when file not found def check_to_write_file(file): try: new_file = open(file, 'w') return new_file except TypeError: print({f'Sorry, {file} is not a file'}) except FileNotFoundError: print({f'Sorry, the file {file} does not exist'}) #prints exception when file not found def check_to_read_file(file): try: new_file = open(file, 'r') return new_file except TypeError: print({f'Sorry, {file} is not a file'}) except FileNotFoundError: print({f'Sorry, the file {file} does not exist'})
#!/usr/bin/env python from Tkinter import * class Graph(Canvas): def __init__(self, parent= None, **kw): Canvas.__init__(self,parent, kw) # self.create_rectangle(10,10,30,30,fill="green") self.rangex=(0,10) self.rangey=(0,10) self.xtics=10 self.ytics=10 self.xlabel="x" self.ylabel="y" self.startx = 30 self.endx = self.winfo_reqwidth()-20 self.starty = self.winfo_reqheight()-20 self.endy = 20 self.points = [] self.lastpoint = () def reset(self): self.points = [] self.lastpoint = () self.refresh() def draw_background(self): self.create_rectangle(0,0,self.winfo_reqwidth(),self.winfo_reqheight(),fill="white") def refresh(self): self.draw_background() self.drawaxis() self.drawlabels() for p in self.points: self.mkpoint(p) self.connect_points() def drawlabels(self): startx = self.startx endx = self.endx starty = self.starty endy = self.endy self.create_text(endx-10,starty+10, text=self.xlabel, font=("courier","10","normal")) self.create_text(startx-10,endy+10, text=self.ylabel, font=("courier","10","normal")) def x_pix_per_value(self): xpix = self.endx - self.startx xr = self.rangex[1]-self.rangex[0] return xpix / xr def y_pix_per_value(self): ypix = self.starty - self.endy yr = self.rangey[1]-self.rangey[0] return ypix / yr def x_value_to_pix(self, xval): return int(self.startx+xval*self.x_pix_per_value()) def y_value_to_pix(self, yval): return int(self.starty - yval*self.y_pix_per_value()) def drawaxis(self): startx = self.startx endx = self.endx starty = self.starty endy = self.endy #y axis self.create_line(startx, starty, startx, endy, width=1) #x axis self.create_line(startx, starty, endx, starty, width=1) xtics_list = [t-self.rangex[0] for t in range(self.rangex[0],self.rangex[1],self.xtics)] ytics_list = [t-self.rangey[0] for t in range(int(self.rangey[0]),int(self.rangey[1]),self.ytics)] for t in xtics_list: x = self.x_value_to_pix(t) self.create_line(x, starty+2, x,starty-2 ) self.create_text(x, starty+7, text=str(t), font=("courier","10","normal")) for t in ytics_list: y = self.y_value_to_pix(t) self.create_line(startx-2, y, startx+2, y) self.create_text(startx-4, y, text=str(t), anchor="e", font=("courier","10","normal")) def add_point(self,xval,yval): p = (xval,yval) self.points.append(p) self.mkpoint(p) self.connect_to_point(p) self.lastpoint = p def mkpoint(self, p): self.create_rectangle( self.x_value_to_pix(p[0])-2, self.y_value_to_pix(p[1])-2, self.x_value_to_pix(p[0])+2, self.y_value_to_pix(p[1])+2, fill="red") def connect_to_point(self, p): if self.lastpoint: self.create_line( self.x_value_to_pix(self.lastpoint[0]),self.y_value_to_pix(self.lastpoint[1]), self.x_value_to_pix(p[0]),self.y_value_to_pix(p[1]), fill="blue", width=2) def connect_points(self): if len(self.points) > 1: tmp = self.lastpoint self.lastpoint = self.points[0] for p in self.points[1:]: self.connect_to_point(p) self.lastpoint = p self.lastpoint = tmp
import random import curses import time import numpy as np import tty import sys import termios # TODO: also have a Food class which is basically just a coordinates and a type (less than, greater than) # We can then have a Screen class which has Food (composition), it has statements and it has a Zoo. FOOD_TYPE = curses.ACS_GEQUAL snake_type = curses.ACS_LANTERN MAX_SPEED = 15 def UpdateSpeed(nFoodsEaten, factor, init_speed): ''' Function to update the speed of the snake Parameters; nFoodsEaten: integer, the number of foods eaten up until now factor: float, indicates how quickly we increase the speed init_speed: float, initial speed of snake returns: int, new speed of snake ''' nUpdates = nFoodsEaten // 2 # update speed after every 2 foods eaten new_speed = int(init_speed * factor ** nUpdates) if new_speed < 15: # maximum speed of 15 new_speed = 15 return new_speed def get_user_difficulty_input() -> str: user_input = 0 while user_input not in [chr(118), chr(104), chr(109)]: user_input = sys.stdin.read(1)[0] print(f"You pressed {user_input}") return user_input class Snake: def __init__(self, up, down, left, right, init_speed, factor_speed_increase, ): # TODO: let snake_type also be part of snake (its shape). Also the snake has a set of colours and it can # change colour or not self.snake_body = [] self.up = up self.down = down self.left = left self.right = right self.speed = init_speed self.factor_speed_increase = factor_speed_increase self.last_key_pressed = self.left # TODO: each snake starts with an initial direction, and has a self.last_key, the last key that was pressed # then when a new key gets pressed we just apply that to all snakes, and if there's a snake for which that # key is actually an input then it updates last_key and it moves, otherwise it just keeps moving into lastkey # so there's a move() function on the screen or whatever and it moves all snakes in a loop. I guess the snake # itself should have a move() too and it takes in a new key and checks it against its own internal keys. def initialize_snake(self, head_x, head_y): # initial snake coordinates #snk_x = sw / 4 # x coordinate of snake #snk_y = sh / 2 # y coordinate of snake self.snake_body = [ [head_y, head_x], # head of snake [head_y, head_x - 1], [head_y, head_x - 2], ] def increase_speed(self): self.speed = self.speed * self.factor_speed_increase if self.speed > MAX_SPEED: self.speed = MAX_SPEED def add_new_head(self, new_head_): self.snake_body.insert(0, new_head_) # insert new head in snake def get_new_head(self, key_pressed) -> list: """ Function to calculate the new position of the head of the snake Parameters; key_pressed: the key that is pressed by user return: new coordinates of the head of the snake. Return empty list if no valid key has been pressed """ new_head = [self.snake_body[0][0], self.snake_body[0][1]] # position the new head at the current head # update new head if key_pressed == self.down: new_head[0] += 1 elif key_pressed == self.up: new_head[0] -= 1 elif key_pressed == self.left: new_head[1] -= 1 elif key_pressed == self.right: new_head[1] += 1 else: return self.get_new_head(self.last_key_pressed) # key other than up, down, left, right is pressed self.last_key_pressed = key_pressed return new_head def move(self, new_key): new_head_position = self.get_new_head(new_key) self.add_new_head(new_head_position) def get_tail(self): return self.snake_body.pop() class MediumSnake(Snake): def __init__(self, up, down, left, right): super().__init__(up, down, left, right, 180, 0.9) class HardSnake(Snake): def __init__(self, up, down, left, right): super().__init__(up, down, left, right, 20, 1) class VeryHardSnake(Snake): def __init__(self, up, down, left, right): super().__init__(up, down, left, right, 110, 0.85) class Zoo: def __init__(self, width, height): self.snake_list = [] self.num_snakes = 0 self.width = width self.height = height def get_snake_init_coords(self): if self.num_snakes == 0: return self.width // 4, self.height // 2 elif self.num_snakes == 1: return self.width // 2, self.height // 5 else: raise NotImplemented("Do some randomized initial position of more snakes!!") def add_snake(self, type_snake, up, down, left, right): if type_snake == "h": snake = HardSnake(up, down, left, right) elif type_snake == "m": snake = MediumSnake(up, down, left, right) elif type_snake == "v": snake = VeryHardSnake(up, down, left, right) else: raise ValueError(f"unknown type snake {type_snake}") self.num_snakes += 1 snake_start_x, snake_start_y = self.get_snake_init_coords() snake.initialize_snake(snake_start_x, snake_start_y) self.snake_list.append(snake) def get_all_coordinates(self): if not self.snake_list: raise RuntimeError("No snakes present!") coordinates = [] for ii in range(self.num_snakes): coordinates.extend(self.snake_list[ii].snake_body) return coordinates class Screen: def __init__(self): self.window = None self.zoo = None self.food = None orig_settings = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings) self.screen = curses.initscr() # initialise screen. self.height, self.width = self.get_screen_dimensions() curses.curs_set(False) # set cursor to 0 so that it doesn't show up in screen curses.noecho() # don't show in terminal when something is typed self.set_up_colours() self.obstacle_coordinates = [] # store coordinates of the obstacles that kill the snake # create initial window with some food in it self.init_window() self._add_food_to_screen(self.height // 2, self.width // 2) def add_zoo(self, zoo): self.zoo = zoo def init_window(self): self.window = curses.newwin(self.height, self.width, 0, 0) self.window.keypad(True) self.window.timeout(10) # TODO: what do here? Need difficulty?? Set later? def get_food_position(self): snake_coordinates = self.zoo.get_all_coordinates() food = None while food is None: new_food = [ random.randint(5, self.height - 5), random.randint(5, self.width - 5) ] if new_food not in snake_coordinates: food = new_food return food def _add_food_to_screen(self, food_x, food_y): self.window.addch(food_x, food_y, FOOD_TYPE) self.food = [food_x, food_y] def add_food(self): food = self.get_food_position() self._add_food_to_screen(food[0], food[1]) def move_snakes(self, new_key): # TODO: do we first want to move all snakes, and then check whether food is eaten and # regenerate? Otherwise the new food might be exactly in front of a snake who then # immediately eats it? for single_snake in self.zoo.snake_list: single_snake.move(new_key) if single_snake[0] == self.food: # food has been eaten self.add_food() else: tail = single_snake.get_tail() self.remove_pixel(tail) def remove_pixel(self, pixel_coord): self.window.addch(pixel_coord[0], pixel_coord[1], ' ') def update_window(self): pass def get_screen_dimensions(self): return self.screen.getmaxyx() def print_starting_message(self) -> None: print('Welcome to Hanne Snake.\nGOAL: eat 40 foods!\n') print('Food is represented by greater-than-or-equal signs. AVOID the less-than-or-equal signs!!') print('You are allowed to hit yourself, but not the walls') print('The number of eaten foods is shown in the top left corner.') print('What difficulty do you want to play??\nvery hard (v)\nhard (h)\nmedium (m)\n') print('Give your input (v, h or m): ') @staticmethod def set_up_colours(): curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) # define colourpair(1) to be (foreground colour, background colour) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(6, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_GREEN) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_YELLOW) curses.init_pair(5, curses.COLOR_RED, curses.COLOR_RED) def play_game(): # set up screen and zoo screen = Screen() zoo = Zoo(screen.width, screen.height) # print user message, get user input screen.print_starting_message() difficulty = get_user_difficulty_input() # TODO: get number of snakes here too. Start with option of 1 and 2 # add snakes to zoo zoo.add_snake(difficulty, curses.KEY_UP, curses.KEY_DOWN, curses.KEY_LEFT, curses.KEY_RIGHT) # add zoo to screen screen.add_zoo(zoo) old_key = curses.KEY_RIGHT while True: new_key = screen.window.getch() # get character that is pressed new_key = old_key if new_key == -1 else new_key # get either nothing or next key. -1 is returned if no input (and then the key remains the same) # Move head of snake screen.move_snake(old_key, new_key) try_head = MoveHead(key, snake) #propose a new head position if try_head != -1: #if up, down, left, right or pause new_head = try_head else: #if any other key, pretend nothing happened and just use the old key again new_head = MoveHead(old_key, snake) key = old_key snake.insert(0, new_head) #insert new head in snake if snake[0] == food: nFoodsEaten += 1; nb = 0 w.addstr(0,0, str('%d' % nFoodsEaten)) w.refresh food = None while food is None: #try to generate new food, if None then try again, etc... new_food = [ random.randint(5, sh - 5), random.randint(5, sw - 5) ] food = new_food if new_food not in snake else None w.addch(food[0], food[1], food_type) #add the food to the screen else: #only remove tail if we did not hit some food (we want snake to become longer if we did hit food) tail = snake.pop() #grab tail coordinates (last item in snake) and remove it from snake w.addch(tail[0], tail[1], ' ') #make current tail disappear (as we just moved away) #update the snake speed. new_speed = UpdateSpeed(nFoodsEaten, factorSpeed, init_speed) w.timeout(new_speed) def generate_food(width, height, excluded): # TODO: think about this. excluded is initially just the snake, but can later be multiple snakes. It's all the # coordinates that are filled. We need to have a Zoo class which contains snakes, can specify the number of snakes # it creates the snakes and keeps track of the coordinates that are occupied by snakes. food = None while food is None: # try to generate new food, if None then try again, etc... new_food = [ random.randint(5, sh - 5), random.randint(5, sw - 5) ] food = new_food if new_food not in snake else None key = curses.KEY_RIGHT nFoodsEaten = 0 snake = Snake() while True: # GET KEY next_key = w.getch() # get character that is pressed old_key = key key = key if next_key == -1 else next_key # get either nothing or next key. -1 is returned if no input (and then the key remains the same) # Move head of snake new_head = snake.get_new_head(key) if not new_head: new_head = snake.get_new_head(old_key) key = old_key # update snake snake.update(new_head) if snake.snake[0] == food: nFoodsEaten += 1; nb = 0 # TODO: class for printing stuff to screen. Screen.printfood(x) does the num_food_eaten printing w.addstr(0, 0, str('%d' % nFoodsEaten)) w.refresh food = None while food is None: # try to generate new food, if None then try again, etc... new_food = [ random.randint(5, sh - 5), random.randint(5, sw - 5) ] food = new_food if new_food not in snake else None w.addch(food[0], food[1], food_type) # add the food to the screen else: # only remove tail if we did not hit some food (we want snake to become longer if we did hit food) tail = snake.pop() # grab tail coordinates (last item in snake) and remove it from snake w.addch(tail[0], tail[1], ' ') # make current tail disappear (as we just moved away) # update the snake speed. new_speed = UpdateSpeed(nFoodsEaten, factorSpeed, init_speed) w.timeout(new_speed) # motivational statements if nFoodsEaten == 2: # w.addstr(0,sw/2-5, 'Keep going!', curses.color_pair(1), curses.A_STANDOUT) w.addstr(0, sw / 2 - 5, 'Keep going!', curses.A_STANDOUT) elif nFoodsEaten == 20: w.addstr(0, sw / 2 - 5, 'Halfway there!', curses.A_STANDOUT) elif nFoodsEaten == 30: w.addstr(0, sw / 2 - 5, 'You are doing well!!', curses.A_STANDOUT) elif nFoodsEaten == 35: w.addstr(0, sw / 2 - 5, 'Just a few more!', curses.A_STANDOUT) # game is won ############################################################## if nFoodsEaten == 40: w.addstr(sh / 2, sw / 2 - 9, 'CONGRATS! YOU WIN!', curses.color_pair(1)) w.refresh(); time.sleep(1) for i in range(sw / 8): x = i * 8 for j in range(22): w.addstr(j, x, '=^..^=', curses.color_pair(2)) w.addstr(sh - 1 - j, x, '=^..^=', curses.color_pair(6)) for i in range(120): y = random.randint(1, sh - 1); x = random.randint(1, sw - 7) w.addstr(y, x, '=^..^=', curses.color_pair(1)) w.refresh() time.sleep(0.1) time.sleep(5) curses.endwin() break # game is lost ############################################################## if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or tuple( snake[0]) in lessThanCoord: # or snake[0] in snake[1:]: for i in range(5): w.addstr(sh / 2 + i, sw / 2 - 5, 'YOU LOSE', curses.color_pair(1)) w.refresh() time.sleep(0.2) time.sleep(1) # print cats for i in range(50): y = random.randint(1, sh - 1) x = random.randint(1, sw - 7) w.addstr(y, x, '=^..^=', curses.color_pair(2)) w.refresh() time.sleep(5) curses.endwin() break ############################################################## # add new head of snake, change colours color = int(np.floor(nIter / 10.0)) % 3 + 3 # every 10 iterations, change colour of snake w.addch(snake[0][0], snake[0][1], snake_type, curses.color_pair(color)) # add new head to snake # add less than or equal signs after every 5 foods eaten if nFoodsEaten % 5 == 0 and nb < limit_lessthan: lessthan = None while lessthan is None: new_lessthan = ( random.randint(1, sh - 5), random.randint(1, sw - 5) ) if new_lessthan not in snake \ and new_lessthan[0] not in range(snake[0][0] - 5, snake[0][0] + 5) \ and new_lessthan[1] not in range(snake[0][1] - 5, snake[0][1] + 5): lessthan = new_lessthan else: lessthan = None w.addch(lessthan[0], lessthan[1], curses.ACS_LEQUAL) lessThanCoord.append(lessthan) nb += 1 nIter += 1
#!/usr/bin/python # # trie.py, # A trie. (Not optimised for character space.) # # Chris Roeder, 2010-02-01, Python 2.6 import node substringsFilename = "substrings.txt" wordsFilename = "top100k.txt" #wordsFilename = "top10k.txt" #wordsFilename = "top1k.txt" #wordsFilename = "top100.txt" #wordsFilename = "top20.txt" #wordsFilename = "test.txt" class trie: def __init__(self): self.root=None def printme(self): self.root.printme(" ") def insert_file(self,filename): count=0 f = open(filename) self.root = node.node('0') for line in f: pointer = self.root line = line[:-1] charcount=0 for c in line: charcount+=1 pointer = pointer.add(c,(charcount == len(line))) def is_word(self, word): pointer=self.root for c in word: pointer = pointer.get(c) if not pointer: return 0 return pointer.is_end == 1 def is_part_of_word(self, word): pointer=self.root for c in word: pointer = pointer.get(c) if not pointer: return 0 return 1 def return_matching_substrings(self,word): matches=[] building_word="" pointer=self.root for c in word: print c building_word += c pointer = pointer.get(c) if not pointer: return matches if pointer.is_end: matches.append(building_word) return matches :q def test_substrings(): t=trie() t.insert_file(substringsFilename) t.printme() print "-------------" my_matches = t.return_matching_substrings("gustavos") print "-------------" for m in my_matches: print m def test(): t = trie() t.insert_file(wordsFilename) t.printme() if (t.is_word("the")): print "the is a word" if (t.is_word("xxx")): print "the is a word" else: print "xxx is not a word" if (t.is_part_of_word("their")): print "their is a word" else: print "their is not a word" if (t.is_part_of_word("thei")): print "thei is a word" else: print "thei is not a word" if (t.is_part_of_word("they")): print "they is a word" else: print "they is not a word" if (t.is_part_of_word("th")): print "th is a word" else: print "th is not a word" if (t.is_part_of_word("t")): print "t is a word" else: print "th is not a word" ##test() test_substrings();
#!/usr/bin/python3 def search(arr, n, x): for i in range(0, n): if arr[i] == x: return i return -1
# #Kevin Nguyen #Basic program for Python that outputs the binary representation of a value. 1 Byte = 8 Bits. Truncating could be improved. # #How to run (linux): # 1.) open command line and cd into directory folder of where this code is # 2.) type in "python PythonGetBytes.py" #import statements import sys; import array; import math; #function implementation/definition below def formatBinary(binaryString): #local declaratoins i, limit, length = 0, 0, len(binaryString); temp, newBinaryString = "", ""; if(length == 8): #length is 8? then output original binarystring return binaryString elif(length < 8): #length is less than 8? append extra 0s as needed limit = 8 - length; #limit when iterating with loop #loop through up to limit and concatenate 0s to temp string while(i < limit): temp += "0"; #concatenate 0s to temp string here i=i+1; newBinaryString = temp + binaryString; #combine temp string with binarystring else: #truncate extra 0s as needed (NOTE: This could be done better to consider sign-bits & significant bits?) limit = length - 8; newBinaryString = binaryString[limit:]; #get substring and set to result return newBinaryString; #return results #main driver below value = 259 #<--- value for representation binaryString = "{0:b}".format(abs(value)); print "Value: " + str(value); print "Initial Binary: " + binaryString; binaryString = formatBinary(binaryString); print "Formatted Binary: " + binaryString;
#IMPORTING THE LIBRARIES import numpy as np import matplotlib.pyplot as plt import pandas as pd #IMPORTING THE DATASET dataset = pd.read_csv('Position_Salaries.csv') X=dataset.iloc[:, 1:-1].values y=dataset.iloc[:, -1].values #TRAINING LINEAR REGRESSION ON WHOLE DATASET from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(X, y) #TRAINING POLYNOMIAL REGRESSION ON WHOLE DATASET from sklearn.preprocessing import PolynomialFeatures poly_reg = PolynomialFeatures(degree = 4) X_poly = poly_reg.fit_transform(X) lin_reg_2 = LinearRegression() lin_reg_2.fit(X_poly, y) #VISUALIZING THE LINEAR REGRESSION RESULTS plt.scatter(X, y, color = 'red') plt.plot(X, lin_reg.predict(X), color = 'blue') plt.title('Truth or Bluff (Linear Regression)') plt.xlabel('Position Level') plt.ylabel('Salary') plt.show() #VISUALIZING THE POLYNOMIAL REGRESSION RESULTS plt.scatter(X, y, color='red') plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color='blue') plt.title('True or False Salary(Polynomial Regression)') plt.xlabel('position') plt.ylabel('salary') plt.show() #VISUALIZIN THE POLYNOMIAL REGRESSION RESULTS #FOR HIGHER RESOLUTION AND SMOOTHER CURVE X_grid = np.arange(min(X), max(X), 0.1) X_grid = X_grid.reshape((len(X_grid), 1)) plt.scatter(X, y, color = 'red') plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = 'blue') plt.title('Truth or Bluff (Polynomial Regression)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() #PREDICTION A NEW RESULT USING POLYNOMIAL REGRESSION salary = lin_reg.predict([[6.5]]) #[[]] 2d array #salary = 330379 #PREDICTION A NEW RESULT USING POLYNOMIAL REGRESSION salary_poly = lin_reg_2.predict(poly_reg.fit_transform([[6.5]])) #salary =158862
import random N = int(input('Введите количество чисел в массиве: ')) array = [random.randint(-N, N) for _ in range(N)] if array[0] < array[1]: min_idx_1 = 1 min_idx_2 = 0 else: min_idx_1 = 0 min_idx_2 = 1 print(array) for i in range (2, N): if array[i] < array[min_idx_1]: spam = min_idx_1 min_idx_1 = i if array[spam] < array[min_idx_2]: min_idx_2 = spam elif array[i] < array[min_idx_2]: min_idx_2 = i print(array[min_idx_2], array[min_idx_1])
# 1. Определение количества различных подстрок с использованием хеш-функции. # Требуется вернуть количество различных подстрок в этой строке. import hashlib def substring_count(input_string): input_string = str(input_string).lower() length = len(input_string) hash_set = set() for i in range(length + 1): for j in range(i + 1, length + 1): h = hashlib.sha1(input_string[i:j].encode('utf-8')).hexdigest() hash_set.add(h) return len(hash_set) some_string = 'hello' print(f'Количество различных подстрок в строке {some_string}: {substring_count(some_string)}')
# https://stackabuse.com/k-means-clustering-with-scikit-learn/ # https://towardsdatascience.com/understanding-k-means-clustering-in-machine-learning-6a6e67336aa1 # https://scikit-learn.org/stable/modules/clustering.html#clustering-performance-evaluation import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import metrics import time as time satdata = pd.read_csv("./../data/sat_data.csv") pendata = pd.read_csv("./../data/pen_data.csv") Xsat = satdata.iloc[:, :-1].values ysat = satdata.iloc[:, 36].values Xpen = pendata.iloc[:, :-1].values ypen = pendata.iloc[:, 16].values from sklearn.model_selection import train_test_split X_train_sat, X_test_sat, y_train_sat, y_test_sat = train_test_split(Xsat, ysat, test_size=0.20) X_train_pen, X_test_pen, y_train_pen, y_test_pen = train_test_split(Xpen, ypen, test_size=0.20) from sklearn.preprocessing import StandardScaler pen_scaler = StandardScaler() sat_scaler = StandardScaler() #We normalize the values so the kmeans doesn't gravitate towards very high values X_train_pen_og = pen_scaler.fit_transform(X_train_pen) X_train_sat_og = sat_scaler.fit_transform(X_train_sat) X_test_pen_og = pen_scaler.fit_transform(X_test_pen) X_test_sat_og = sat_scaler.fit_transform(X_test_sat) pen_time = 0 sat_time = 0 pen_accuracy = [] sat_accuracy = [] sat_homog = [] pen_homog = [] sat_comp = [] sat_comp_train = [] sat_comp_test = [] pen_comp = [] pen_comp_train = [] pen_comp_test = [] sat_v = [] pen_v = [] y_train_sat = [label - 1 for label in y_train_sat] y_test_sat = [label - 1 for label in y_test_sat] #=========================================================1. Uncomment to produce plots A, B, C===================================== # for i in range(1, 21): # from sklearn.cluster import KMeans # kmeans_sat = KMeans(n_clusters = i) # 7 categories, domain knowledge # kmeans_pen = KMeans(n_clusters = i) # 10 categories, domain knowledge # start_time = time.time() # kmeans_sat.fit(X_train_sat_og) # sat_labels = kmeans_sat.labels_ # sat_labels_train = kmeans_sat.labels_ # sat_labels_test = kmeans_sat.predict(X_test_sat_og) # end_time = time.time() # sat_time = end_time - start_time # start_time = time.time() # kmeans_pen.fit(X_train_pen_og) # pen_labels = kmeans_pen.labels_ # pen_labels_train = kmeans_pen.labels_ # pen_labels_test = kmeans_pen.predict(X_test_pen_og) # end_time = time.time() # pen_time = end_time - start_time #================================================================================================================================ #================================================2. Uncomment to calculate homogeneity measures (Use plot C)======================== # comp = metrics.homogeneity_score(sat_labels_train, y_train_sat) # sat_comp_train.append(comp) # comp = metrics.homogeneity_score(sat_labels_test, y_test_sat) # sat_comp_test.append(comp) # comp = metrics.homogeneity_score(pen_labels_train, y_train_pen) # pen_comp_train.append(comp) # comp = metrics.homogeneity_score(pen_labels_test, y_test_pen) # pen_comp_test.append(comp) #==============3. Uncomment to view homogeneity, completeness, and v measure for satellite and digits data (Use plot B)================ # homog, comp, v = metrics.homogeneity_completeness_v_measure(sat_labels, y_train_sat) # sat_homog.append(homog) # sat_comp.append(comp) # sat_v.append(v) # homog, comp, v = metrics.homogeneity_completeness_v_measure(pen_labels, y_train_pen) # pen_homog.append(homog) # pen_comp.append(comp) # pen_v.append(v) #=================================================================================================================================== #======================4. Uncomment to permute predicted labels and compute accuracy (Use Plot A)======================= # pred_sat_labels = kmeans_sat.predict(X_test_sat) # pred_pen_labels = kmeans_pen.predict(X_test_pen) # from scipy.stats import mode # # match true labels with the labels generated by the algorithm so we can compare accuracy # sat_labels = np.zeros_like(pred_sat_labels) # for i in range(1,8): # mask = (pred_sat_labels == i) # sat_labels[mask] = mode(y_test_sat[mask])[0] # from sklearn.metrics import accuracy_score # sat_accuracy.append(accuracy_score(y_test_sat, sat_labels)) # pen_labels = np.zeros_like(pred_pen_labels) # for i in range(10): # mask = (pred_pen_labels == i) # pen_labels[mask] = mode(y_test_pen[mask])[0] # pen_accuracy.append(accuracy_score(y_test_pen, pen_labels)) # sat_error = [1 - accuracy for accuracy in sat_accuracy] # pen_error = [1 - accuracy for accuracy in pen_accuracy] #=================================================================================================================================== #=======================================Plot A====================================================================================== # plt.figure(figsize=(12, 6)) # plt.plot(range(10, 101), sat_error, label='Testing Error', color='red', linestyle='solid', marker='') # plt.title('Error Rate vs Number of Iterations - KMeans (Satellite)') # plt.xlabel('Number of Iterations') # plt.ylabel('Error') # plt.show() # plt.figure(figsize=(12, 6)) # plt.plot(range(10, 101), pen_error, label='Testing Error', color='red', linestyle='solid', marker='') # plt.title('Error Rate vs Number of Iterations - KMeans (Digits)') # plt.xlabel('Number of Iterations') # plt.ylabel('Error') # plt.show() #=================================================================================================================================== #===================================Plot B========================================================================================== # plt.figure(figsize=(12, 6)) # plt.plot(range(1, 21), sat_comp, label='Completeness', color='red', linestyle='solid', marker='') # plt.plot(range(1, 21), sat_homog, label='Homogeneity', color='green', linestyle='solid', marker='') # plt.plot(range(1, 21), sat_v, label='V-Measure', color='blue', linestyle='solid', marker='') # plt.title('Homogeneity, Completeness, and V Measure vs. Number of Components - KMeans (Satellite)') # plt.xlabel('Number of Components') # plt.ylabel('Score') # plt.legend() # plt.show() # plt.figure(figsize=(12, 6)) # plt.plot(range(1, 21), pen_comp, label='Completeness', color='red', linestyle='solid', marker='') # plt.plot(range(1, 21), pen_homog, label='Homogeneity', color='green', linestyle='solid', marker='') # plt.plot(range(1, 21), pen_v, label='V-Measure', color='blue', linestyle='solid', marker='') # plt.title('Homogeneity, Completeness, and V Measure vs. Number of Components - KMeans (Digits)') # plt.xlabel('Number of Components') # plt.ylabel('Score') # plt.legend() # plt.show() #================================================================================================================================== # =======Plot C: Use to show completeness in the testing and training data========================================================= # plt.figure(figsize=(12, 6)) # plt.plot(range(1, 21), sat_comp_train, label='Train', color='red', linestyle='solid', marker='') # plt.plot(range(1, 21), sat_comp_test, label='Test', color='green', linestyle='solid', marker='') # plt.title('Homogeneity (Test and Train) vs. Number of Components - KMeans (Satellite)') # plt.xlabel('Number of Components') # plt.ylabel('Homogeneity') # plt.legend() # plt.show() # plt.figure(figsize=(12, 6)) # plt.plot(range(1, 21), pen_comp_train, label='Train', color='red', linestyle='solid', marker='') # plt.plot(range(1, 21), pen_comp_test, label='Test', color='green', linestyle='solid', marker='') # plt.title('Homogeneity (Test and Train) vs. Number of Components - KMeans (Digits)') # plt.xlabel('Number of Components') # plt.ylabel('Homogeneity') # plt.legend() # plt.show() #===================================================================================================================== #==============================5. Uncomment to examine the homogeneity in Kmeans using different feature selection algorithms===================== # algs = ['PCA','ICA','Random Projections','Feature Agglomeration'] # sat_homog = [] # pen_homog = [] # from sklearn.decomposition import PCA # sat_pca = PCA(n_components=20) # pen_pca = PCA(n_components=10) # X_train_sat = sat_pca.fit_transform(X_train_sat_og) # X_train_pen = pen_pca.fit_transform(X_train_pen_og) # from sklearn.cluster import KMeans # kmeans_sat = KMeans(n_clusters = 6) # kmeans_pen = KMeans(n_clusters = 11) # sat_labels = kmeans_sat.fit_predict(X_train_sat) # pen_labels = kmeans_pen.fit_predict(X_train_pen) # sat_homog.append(metrics.homogeneity_score(sat_labels, y_train_sat)) # pen_homog.append(metrics.homogeneity_score(pen_labels, y_train_pen)) # from sklearn.decomposition import FastICA # sat_ica = FastICA(n_components=20) # pen_ica = FastICA(n_components=10) # X_train_sat = sat_ica.fit_transform(X_train_sat_og) # X_train_pen = pen_ica.fit_transform(X_train_pen_og) # kmeans_sat = KMeans(n_clusters = 6) # kmeans_pen = KMeans(n_clusters = 11) # sat_labels = kmeans_sat.fit_predict(X_train_sat) # pen_labels = kmeans_pen.fit_predict(X_train_pen) # sat_homog.append(metrics.homogeneity_score(sat_labels, y_train_sat)) # pen_homog.append(metrics.homogeneity_score(pen_labels, y_train_pen)) # from sklearn.random_projection import GaussianRandomProjection # sat_rp = GaussianRandomProjection(n_components=20) # pen_rp = GaussianRandomProjection(n_components=10) # X_train_sat = sat_rp.fit_transform(X_train_sat_og) # X_train_pen = pen_rp.fit_transform(X_train_pen_og) # kmeans_sat = KMeans(n_clusters = 6) # kmeans_pen = KMeans(n_clusters = 11) # sat_labels = kmeans_sat.fit_predict(X_train_sat) # pen_labels = kmeans_pen.fit_predict(X_train_pen) # sat_homog.append(metrics.homogeneity_score(sat_labels, y_train_sat)) # pen_homog.append(metrics.homogeneity_score(pen_labels, y_train_pen)) # from sklearn.cluster import FeatureAgglomeration # sat_fa = FeatureAgglomeration(n_clusters=20) # pen_fa = FeatureAgglomeration(n_clusters=10) # X_train_sat = sat_fa.fit_transform(X_train_sat_og) # X_train_pen = pen_fa.fit_transform(X_train_pen_og) # kmeans_sat = KMeans(n_clusters = 6) # kmeans_pen = KMeans(n_clusters = 11) # sat_labels = kmeans_sat.fit_predict(X_train_sat) # pen_labels = kmeans_pen.fit_predict(X_train_pen) # sat_homog.append(metrics.homogeneity_score(sat_labels, y_train_sat)) # pen_homog.append(metrics.homogeneity_score(pen_labels, y_train_pen)) # plt.figure(figsize=(12, 6)) # plt.bar(algs, sat_homog) # plt.title('Homogeneity vs. Dimensionality Reduction Algorithm - KMeans (Satellite)') # plt.xlabel('Dimensionality Reduction Algorithm') # plt.ylabel('Homogeneity') # plt.legend() # plt.show() # plt.figure(figsize=(12, 6)) # plt.bar(algs, pen_homog) # plt.title('Homogeneity vs. Dimensionality Reduction Algorithm - KMeans (Digits)') # plt.xlabel('Dimensionality Reduction Algorithm') # plt.ylabel('Homogeneity') # plt.legend() # plt.show() #============================================================================================================================================ #====6. Uncomment to view how the number of components in feature selection effects the cluster homogeneity for each feature selection algorithm===== sat_homog_alg = [] from sklearn.decomposition import PCA from sklearn.cluster import KMeans kmeans_sat = KMeans(n_clusters = 6) for i in range(2,37): sat_pca = PCA(n_components=i) sat_labels = kmeans_sat.fit_predict(X_train_sat_og) sat_homog.append(metrics.homogeneity_score(sat_labels, y_train_sat)) X_train_sat = sat_pca.fit_transform(X_train_sat_og) sat_labels = kmeans_sat.fit_predict(X_train_sat) sat_homog_alg.append(metrics.homogeneity_score(sat_labels, y_train_sat)) pen_homog_alg = [] kmeans_pen = KMeans(n_clusters = 11) for i in range(2, 17): pen_pca = PCA(n_components=i) pen_labels = kmeans_pen.fit_predict(X_train_pen_og) pen_homog.append(metrics.homogeneity_score(pen_labels, y_train_pen)) X_train_pen = pen_pca.fit_transform(X_train_pen_og) pen_labels = kmeans_pen.fit_predict(X_train_pen) pen_homog_alg.append(metrics.homogeneity_score(pen_labels, y_train_pen)) plt.figure(figsize=(12, 6)) plt.plot(range(2, 37), sat_homog, label='No PCA', color='red', linestyle='solid', marker='') plt.plot(range(2, 37), sat_homog_alg, label='w/ PCA', color='green', linestyle='solid', marker='') plt.title('Homogeneity vs. Number of Features - KMeans (Satellite)') plt.xlabel('Number of Features') plt.ylabel('Homogeneity') plt.legend() plt.show() plt.figure(figsize=(12, 6)) plt.plot(range(2, 17), pen_homog, label='No PCA', color='red', linestyle='solid', marker='') plt.plot(range(2, 17), pen_homog_alg, label='w/ PCA', color='green', linestyle='solid', marker='') plt.title('Homogeneity vs. Number of Features - KMeans (Digits)') plt.xlabel('Number of Features') plt.ylabel('Homogeneity') plt.legend() plt.show() #==================================================================================================================================================
def divide(dividend, divisor): if divisor == 0: raise ZeroDivisionError("Divisor cannot be. ") return dividend / divisor def calculate(*values, operator): return operator(*values)
''' This is a simple straight heads-up poker game. The player and computer are each dealt a 5 card hand, with no drawing. The algorithm uses card counting, combinatorics, probability, Bayes theorem, logistic regression, and heuristics. The computer cannot 'see' the player's cards except if they are revealed at the end of a showdown. The computer card counts to determine the probability of the player having a better hand. At any stage in betting, the computer calculates the probability threshold for which the expectation value of money won is 0, then creates a default average cumulative probability curve for folding. The player's cumulative probability of folding is generated using logistic regression on the last 100 player actions. By comparing the mean cumulative probability to the player's model, the computer determines if the player is cautious or aggressive, and estimates the probability the player is bluffing or will fold prematurely. Using Bayes theorem, the computer recalculates the probability that the player will be under the threshold probability. This is used to update the probability that the player will have a hand that beats the computer's hand. If the probability that the computer's hand is higher plus the probability that the player's hand is higher and the player folds is lower than the threshold, the computer may raise. The frequency of raising is determined by how good the computer's hand is and/or how many successful showdowns have occurred. ''' from random import * from sklearn.linear_model import LogisticRegression from scipy.special import comb from scipy.stats import beta from itertools import * from math import e from collections import deque number = {1:'A',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'10',11:'J',12:'Q',13:'K',14:'A'} symbol={'spade':'\u2660','heart':'\u2665','diamond':'\u2666','club':'\u2663'} ranking = {'spade':4,'heart':3,'diamond':2,'club':1} invranking = {4:'spade',3:'heart',2:'diamond',1:'club'} handranking = ['nopair','onepair','twopair','threekind','straight','flush','fullhouse','fourkind','straightflush'] # Product Function def product(x): y = 1 for i in x: y = y*i return y # Card class class card(): def __init__(self,suit,value): self.suit = suit self.value = value self.rank = (self.value-2)*4+ranking[self.suit] def printcard(self): print(number[self.value]+symbol[self.suit]) # Pile of cards class pile(): def __init__(self): self.cards = [] self.size = 0 def shuffle(self): shuffle(self.cards) def draw(self): self.size -= 1 return self.cards.pop() def place(self,card): self.cards.append(card) self.size+=1 # Deck of cards class deck(pile): def __init__(self): # Initializes with all 52 cards super().__init__() for i in ['spade','heart','diamond','club']: for j in range(2,15): if str(j)+i not in globals().keys(): # Prevents creating duplicate cards for computer deck globals().update({str(j)+i:card(i,j)}) self.cards.append(globals()[str(j)+i]) self.size = 52 self.calccomb() def valuecount(self): # Stores counts of each card value self.valuedict = {2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14:0} for x in [a.value for a in self.cards]: self.valuedict[x]+=1 def straightflush(self): # Combinations of a straight flush given a deck self.straightflushcomb = {} # List of highest card in hand and probability of associated straight flush for i in ['spade', 'heart', 'diamond', 'club']: for j in range(2, 15): if j >= 5 and globals()[str(j) + i] in self.cards: # Note: 2-4 cannot be the highest card counter = 0 for k in range(j-4, j): # The required 4 preceding values for a straight flush if k != 1: # Aces counted as 14 if globals()[str(k) + i] in self.cards: # Counts if card is present in deck counter += 1 if j == 5 and globals()[str(14) + i] in self.cards: # For the case of A 2 3 4 5, where 5 is high counter += 1 self.straightflushcomb.update({str(j) + i: counter//4}) # All 4 cards must be present else: self.straightflushcomb.update({str(j) + i: 0}) # Combos of a flush is the number of choices of 4 cards from however many are lower than the high of that suit def flush(self): self.flushcomb = {} for i in ['spade', 'heart', 'diamond', 'club']: for j in range(2, 15): if j>=6 and globals()[str(j) + i] in self.cards: # Since A is 14, high card is never lower than 6 counter = 0 for k in range(2, j): # Count all cards lower than the high card with the same suit if globals()[str(k)+i] in self.cards: counter += 1 if j == 14: # Subtract straight flushes and case of A 2 3 4 5 for Ace self.flushcomb.update({str(j) + i: comb(counter, 4) - self.straightflushcomb[str(5) + i]- self.straightflushcomb[str(j) + i]}) else: # For others subtract combinations that are straight flushes self.flushcomb.update({str(j) + i: comb(counter, 4)-self.straightflushcomb[str(j) + i]}) else: self.flushcomb.update({str(j) + i: 0}) # Combos of a straight is the product of the number of each card of required value def straight(self): self.straightcomb = {} for i in ['spade', 'heart', 'diamond', 'club']: for j in range(2, 15): if j >= 5 and globals()[str(j) + i] in self.cards: # Note: 2-4 cannot be the highest card counts = [] for k in range(j - 4, j): # Create a list of numbers of cards of required value if k != 1: if self.valuedict[k] > 0: counts.append(self.valuedict[k]) if j == 5 and self.valuedict[14]>0: # For A 2 3 4 5, include count for Ace (recorded as 14) counts.append(self.valuedict[14]) self.straightcomb.update({str(j) + i: (len(counts) // 4)*product(counts) -self.straightflushcomb[str(j) + i]}) #Subtract straight flush else: self.straightcomb.update({str(j) + i: 0}) # Combos given a high card, is sum of products of number of cards of each value, over combinations of size 4 def nopair(self): self.nopaircomb = {} for i in ['spade', 'heart', 'diamond', 'club']: for j in range(2, 15): if j >= 6 and globals()[str(j) + i] in self.cards: counts = [] for k in range(2, j): if self.valuedict[k] > 0: counts.append(self.valuedict[k]) combos = 0 for a in combinations(counts,4): combos = combos + product(a) if j == 14: # Subtract straight flush, flush, and straight probabilities self.nopaircomb.update({str(j) + i: combos - self.straightflushcomb[str(j) + i] - self.flushcomb[str(j) + i] - self.straightcomb[str(j) + i] - self.straightflushcomb[str(5) + i] - self.straightcomb[str(5) + i]}) else: self.nopaircomb.update({str(j)+i: combos -self.straightflushcomb[str(j) + i]-self.flushcomb[str(j) + i]-self.straightcomb[str(j) + i]}) else: self.nopaircomb.update({str(j) + i: 0}) # Combos of full house def fullhouse(self): self.fullhousecomb = {} for i in ['spade', 'heart', 'diamond', 'club']: for j in range(2, 15): if j>= 3 and globals()[str(j) + i] in self.cards: # If the high card is in the triplet high3comb = 0 if self.valuedict[j]>=3: paircount = 0 for k in range(2,j): if self.valuedict[k]>=2: # Combinations of pairs of lower value than the triplet paircount += comb(self.valuedict[k],2) count = 0 for m in range(1,ranking[i]): # Combinations of suits for the triplet if globals()[str(j)+invranking[m]] in self.cards: count +=1 high3comb = comb(count,2)*paircount high2comb = 0 if self.valuedict[j] >= 2: # If the high card is in the pair triplecount = 0 for k in range(2, j): if self.valuedict[k] >= 3: # Combinations of triplets lower than the pair triplecount += comb(self.valuedict[k], 3) count = 0 for m in range(1, ranking[i]): # Combinations of suits for the pair if globals()[str(j) + invranking[m]] in self.cards: count += 1 high2comb = comb(count, 1) * triplecount self.fullhousecomb.update({str(j)+i:high2comb+high3comb}) # Total combinations else: self.fullhousecomb.update({str(j) + i: 0}) # Combos of a full house containing a triplet (not necessarily having the high card in the triplet) def fullhouse3(self): # For use in calculating combinations of three of a kind self.fullhouse3comb = {} for i in ['spade', 'heart', 'diamond', 'club']: for j in range(2, 15): if globals()[str(j) + i] in self.cards: high3comb = 0 if self.valuedict[j]>=3: paircount = 0 for k in range(2,j): # combinations of lower pairs if self.valuedict[k]>=2: paircount += comb(self.valuedict[k],2) for k in range(j+1,15): # combinations of higher pairs if self.valuedict[k]>=2: paircount += comb(self.valuedict[k],2) count = 0 for m in range(1,ranking[i]): # combinations of suits for the triplet if globals()[str(j)+invranking[m]] in self.cards: count +=1 high3comb = comb(count,2)*paircount self.fullhouse3comb.update({str(j)+i:high3comb}) else: self.fullhouse3comb.update({str(j) + i: 0}) # Combinations of four of a kind, if all 4 in are in the deck, is just the number of remaining cards in the deck def fourkind(self): self.fourkindcomb={} for i in ['spade', 'heart', 'diamond', 'club']: for j in range(2, 15): # Note that the high card in a four of a kind is always a spade if self.valuedict[j] ==4 and i == 'spade': self.fourkindcomb.update({str(j) + i:self.size-4}) else: self.fourkindcomb.update({str(j) + i: 0}) # Combos for 3 of a kind is the combination of suits tiems combos for the remaining 2 cards def threekind(self): self.threekindcomb = {} for i in ['spade', 'heart', 'diamond', 'club']: for j in range(2, 15): if globals()[str(j) + i] in self.cards and self.valuedict[j] >= 3: count = 0 for m in range(1, ranking[i]): # Combinations of suits for the triplet if globals()[str(j) + invranking[m]] in self.cards: count += 1 # Then subtract combos for four of a kind and full house containing the triplet self.threekindcomb.update({str(j) + i:comb(count,2)*comb(self.size-3,2) -self.fourkindcomb[str(j) + 'spade']-self.fullhouse3comb[str(j) + i]}) else: self.threekindcomb.update({str(j) + i: 0}) # Combos for 2 pair is the combos for the suits of the high pair times combos for lower pair def twopair(self): self.twopaircomb = {} for i in ['spade', 'heart', 'diamond', 'club']: for j in range(2, 15): if globals()[str(j) + i] in self.cards and self.valuedict[j] >= 2: count =0 for m in range(1, ranking[i]): # Combinations of suits for high pair if globals()[str(j) + invranking[m]] in self.cards: count += 1 paircount = 0 for k in range(2, j): # Combinations for lower pair if self.valuedict[k] >= 2: paircount += comb(self.valuedict[k], 2)*\ (self.size-4-(self.valuedict[j]-2)-(self.valuedict[k]-2)) self.twopaircomb.update({str(j) + i:comb(count, 1) * paircount}) else: self.twopaircomb.update({str(j) + i: 0}) # Combos for a pair is combos for suits of the pair times combinations of other 3 cards (see no pair calculation) def onepair(self): self.onepaircomb = {} for i in ['spade', 'heart', 'diamond', 'club']: for j in range(2, 15): if globals()[str(j) + i] in self.cards and self.valuedict[j] >= 2: count = 0 for m in range(1, ranking[i]): # Combos of suits for the pair if globals()[str(j) + invranking[m]] in self.cards: count += 1 counts = [] for k in range(2, j): # Counts of cards lower than pair if self.valuedict[k] > 0: counts.append(self.valuedict[k]) for k in range(j+1, 15): # Counts of cards higher than pair if self.valuedict[k] > 0: counts.append(self.valuedict[k]) combos = 0 for a in combinations(counts, 3): # All possible combinations of 3 different values combos = combos + product(a) self.onepaircomb.update({str(j) + i:comb(count, 1)*combos}) else: self.onepaircomb.update({str(j) + i:0}) def calccomb(self): # Calculate the combinations self.valuecount() self.straightflush() self.flush() self.straight() self.nopair() self.fullhouse() self.fullhouse3() self.fourkind() self.threekind() self.twopair() self.onepair() def combos(self,type): # Function returning the combinations of specified hand if type == 'straightflush': return self.straightflushcomb elif type == 'flush': return self.flushcomb elif type == 'straight': return self.straightcomb elif type == 'nopair': return self.nopaircomb elif type == 'fullhouse': return self.fullhouse3comb elif type == 'fourkind': return self.fourkindcomb elif type == 'threekind': return self.threekindcomb elif type == 'twopair': return self.twopaircomb elif type == 'onepair': return self.onepaircomb def totalprob(self,type): # Function returning the probability of specified hand if type == 'straightflush': return sum(self.straightflushcomb.values())/comb(self.size,5) elif type == 'flush': return sum(self.flushcomb.values())/comb(self.size,5) elif type == 'straight': return sum(self.straightcomb.values())/comb(self.size,5) elif type == 'nopair': return sum(self.nopaircomb.values())/comb(self.size,5) elif type == 'fullhouse': return sum(self.fullhouse3comb.values())/comb(self.size,5) elif type == 'fourkind': return sum(self.fourkindcomb.values())/comb(self.size,5) elif type == 'threekind': return sum(self.threekindcomb.values())/comb(self.size,5) elif type == 'twopair': return sum(self.twopaircomb.values())/comb(self.size,5) elif type == 'onepair': return sum(self.onepaircomb.values())/comb(self.size,5) class hand(): # Class of 5 card hands def __init__(self,cards): self.cards = sorted(cards,key = lambda x:x.rank) # Sorted by value of card and suit self.type = None # Type of hand self.max = None # High card in hand def append(self,card): # Add a card to the hand self.cards.append(card) self.cards = sorted(self.cards,key = lambda x:x.rank) def printhand(self): # Print the hand print(' '+number[self.cards[0].value]+symbol[self.cards[0].suit]+' ' +number[self.cards[1].value]+symbol[self.cards[1].suit]+' ' +number[self.cards[2].value]+symbol[self.cards[2].suit]+' ' +number[self.cards[3].value]+symbol[self.cards[3].suit]+' ' +number[self.cards[4].value]+symbol[self.cards[4].suit]+' ') def classify(self): # Classify the hand (assign a type) suits = set([x.suit for x in self.cards]) values = [x.value for x in self.cards] valuecount = {} # A dictionary of the number of each value in the hand maxrep = 0 # The maximum number of any value in the hand for value in values: if value not in valuecount.keys(): valuecount.update({value:1}) else: valuecount[value]+=1 if valuecount[value]>maxrep: maxrep = valuecount[value] if len(suits)==1 and (max(values)-min(values))==4: # Straight flush has only 1 suit and high - low = 4 self.type = 'straightflush' self.max = max(self.cards,key = lambda x:x.rank) # High is the maximum in the hand elif len(suits)==1 and {2,3,4,5,14}==set(values): # For the case of A 1 2 3 4 5 self.type = 'straightflush' self.max = globals()[str(5)+self.cards[3].suit] # When sorted, the 5 has index 3 elif len(suits)==1: # Flush has only 1 suit self.type = 'flush' self.max = max(self.cards, key=lambda x: x.rank) # High is the maximum in the hand elif (max(values)-min(values))==4 and len(valuecount)==5: # Straight has 5 different values and high - low = 4 self.type = 'straight' self.max = max(self.cards, key=lambda x: x.rank) # High is the maximum in the hand elif {2,3,4,5,14}==set(values): # For the case of A 1 2 3 4 5 self.type = 'straight' self.max = globals()[str(5) + self.cards[3].suit] elif maxrep == 4: # The maximum number of cards for a value is 4 self.type = 'fourkind' self.max = globals()[str(values[2]) + 'spade'] elif maxrep == 3 and len(valuecount)==2: # The maximum number of cards for a value is 3, and 2 different values self.type = 'fullhouse' self.max = max(self.cards, key=lambda x: x.rank) # High is the maximum in the hand elif maxrep == 3 and len(valuecount) == 3:# The maximum number of cards for a value is 3, and 3 different values self.type = 'threekind' self.max = max([x for x in self.cards if valuecount[x.value]==3], key=lambda x: x.rank) # Max of the 3 elif maxrep == 2 and len(valuecount) == 3: # The maximum number for a value is 2, and 3 different values self.type = 'twopair' self.max = max([x for x in self.cards if valuecount[x.value] == 2], key=lambda x: x.rank) # Max of 2 pairs elif maxrep == 2 and len(valuecount) == 4: # The maximum number for a value is 2, and 4 different values self.type = 'onepair' self.max = max([x for x in self.cards if valuecount[x.value] == 2], key=lambda x: x.rank) # Max of the pair else: self.type = 'nopair' self.max = max(self.cards,key = lambda x:x.rank) # High is the maximum in the hand def playerprob(deck, hand): # probability of player getting better hand than computer prob = 0 hand.classify() # Classify the computer's hand for i in range (handranking.index(hand.type)+1,len(handranking)): # Calculate probability of higher hands prob += deck.totalprob(handranking[i]) for i in ['spade', 'heart', 'diamond', 'club']: # Calculate probability of same hand but higher high card for j in range(2, 15): if globals()[str(j) + i].rank > hand.max.rank: prob += deck.combos(hand.type)[str(j) + i]/comb(deck.size,5) return prob def beathand(hand1, hand2): # returns True if hand 1 beats hand 2 hand1.classify() hand2.classify() if handranking.index(hand1.type)>handranking.index(hand2.type) or\ (handranking.index(hand1.type) == handranking.index(hand2.type) and hand1.max.rank > hand2.max.rank): return True else: return False def deal(): # Deal cards to player and computer global playerhand global comphand global maindeck global compdeck global compamount global playeramount global pot playerhand = hand([]) for i in range(0, 5): # Cards drawn playerhand.append(maindeck.draw()) comphand = hand([]) for i in range(0, 5): comphand.append(maindeck.draw()) for x in comphand.cards: compdeck.cards.remove(x) playerhand.printhand() # Print player's hand print('') compamount -= minbet # Minimum bet in the pot playeramount -= minbet pot += minbet*2 def endround(): # Procedure for ending a round global playerhand global comphand global discard global lastmoves global pot global compamount global playeramount global totalplayerbet global totalcompbet global first # If both call or if one runs out of money, compare hands to determine who gets the pot if (lastmoves[0] == 'call' and lastmoves[1] == 'call') or\ ((compamount <=0 or playeramount <=0) and lastmoves[1]!='fold'): if beathand(comphand, playerhand): compamount += pot else: playeramount +=pot pot = 0 showhands() printamounts() for x in playerhand.cards: # Add cards to discard pile discard.place(x) for x in comphand.cards: discard.place(x) playerhand = hand([]) # Empty the hands comphand = hand([]) lastmoves = deque([],2) # Reset move queue totalplayerbet = 0 # Reset total player and computer bet amounts totalcompbet = 0 if first != 'player': first = 'player' else: first = 'computer' def showhands(): # For a showdown global comphandsrevealed global compwinsrevealed for x in playerhand.cards: # Revealed player's card gets removed from computer's 'remembered' deck compdeck.cards.remove(x) comphandsrevealed +=1 if beathand(comphand, playerhand)==True: # Keep track of number of showdowns computer wins compwinsrevealed +=1 print('Computer\'s Hand:') # Reveal computer's hand comphand.printhand() def playermove(): # Player move procedure global playeramount global compamount global pot global bet global potprob global Xdata global ydata global playeraction global totalplayerbet move = input('Choose - fold, call, or raise: ') while move not in ['fold','call','raise']: move = input('Choose - fold, call, or raise: ') if move == 'fold': playeraction = 'fold' potprob = (pot-totalplayerbet)/(pot+bet) compamount += pot pot = 0 bet = 0 Xdata.append([potprob]) ydata.append(1) elif move == 'call': playeraction = 'call' potprob = (pot-totalplayerbet)/(pot+bet) playeramount -= bet totalplayerbet +=bet pot += bet bet = 0 Xdata.append([potprob]) ydata.append(0) elif move == 'raise': playeraction = 'raise' if compamount <= 0: print('Computer doesn\'t have enough. Call.') amount = 0 else: amount = int(input('Amount = $')) while amount > playeramount: amount = int(input('You don\'t have enough. Amount = $')) potprob = (pot-totalplayerbet)/(pot+bet+amount) playeramount -= bet totalplayerbet += bet pot += bet bet = amount playeramount -=amount totalplayerbet += amount pot +=amount Xdata.append([potprob]) ydata.append(0) if len(Xdata) > memory: # Computer model built on last specified number of player moves (memory, default 100) Xdata.pop(0) ydata.pop(0) printamounts() def compfold(): # Procedure for computer folding global playeramount global pot global bet playeramount +=pot pot =0 bet = 0 print('Computer folds') def compcall(): # Procedure for computer calling global compamount global pot global bet global totalcompbet totalcompbet+=1 compamount -= bet pot += bet bet = 0 print('Computer calls') def compraise(amount): # Procedure for computer raising global compamount global pot global bet global totalcompbet totalcompbet += 1 compamount -= bet pot += bet bet = amount compamount -= amount totalcompbet += amount pot += amount print('Computer raises $'+str(amount)) # Sensible probability of folding, which is a logistic function of the difference between probability of being beat and # pot probability threshold (this difference is equivalent to the expected amount lost normalized by pot size). # This normalization helps prevent folding when little is on the table or not folding when a lot is on the table. def probfold(potprob,handprob): return 1/(1+e**(-1*w*(handprob-potprob))) def probplayerfold(potprob): # calculates player probability of folding if 0 in ydata and 1 in ydata: model = LogisticRegression(solver='liblinear') model.fit(Xdata, ydata) return model.predict_proba([[potprob]])[0][1] elif 0 in ydata: return 0.05 elif 1 in ydata: return 0.95 else: return 0.5 def estimateopp(potprob): global k global c pfold = probplayerfold(potprob) # player's predicted probability of folding given current pot probability pbeatprior = playerprob(compdeck,comphand) if playeraction != 'Fold': # Bayes Theorem calculates probability given player action if playeraction is None: pbeatposterior = pbeatprior else: pbeatpotposterior = (1+pfold)/2 # Player's probability of beating the computer is updated via Beta function pbeatposterior = 1-beta.cdf(1-pbeatprior,k*pbeatpotposterior,k*(1-pbeatpotposterior)) pbeatposterior = c*pbeatposterior + (1-c)*pbeatprior return (pbeatposterior,pfold) else: return (potprob,0) def compmove(): playerprobs = estimateopp(potprob) compwinprob = playerprobs[0]*playerprobs[1]+(1-playerprobs[0]) foldfreq = probfold(potprob, playerprobs[0]) if comphandsrevealed != 0: # The higher % of showdowns computer wins, the less likely bluffs will be called x = compwinsrevealed / comphandsrevealed else: x = 0.5 raisefreq = 1 / (1 + e ** (-1 * (x - 0.75))) def foldorcall(): if random() < foldfreq: compfold() printamounts() return 'fold' else: compcall() printamounts() return 'call' if compwinprob > (1-potprob): # If odds of winning or player folding is higher than pot odds, computer may raise if compamount >=10 and playeramount > 0: # If odds are in computer's favor, computer has a chance of raising depending on a random number if (pot - totalcompbet) / (pot + bet + 5) > playerprobs[0] and random() < raisefreq: if playeramount < 5: compraise(playeramount) else: compraise(5) printamounts() return 'raise' # But if hand is particularly good, computer will raise anyways elif (pot - totalcompbet) / (pot + bet + 10)/ (1 - compwinprob ) > 6 and\ (pot - totalcompbet) / (pot + bet + 10) > playerprobs[0]: # Computer raise restricted to 10 to prevent player from folding early raisefreq = compwinprob/(1+e**(-0.1*(compamount-compthreshold))) # Less likely to raise if less money if random() < raisefreq: if playeramount < 10: compraise(playeramount) else: compraise(10) printamounts() return 'raise' else: if lastmoves[1] == 'call':# If player calls, computer will call since it doesn't lose anything compcall() printamounts() return 'call' else: if playeraction is None: # If the computer goes first, there is nothing saved by folding. compcall() printamounts() return 'call' else: return foldorcall() # Still fairly good hand, but smaller raise elif (pot - totalcompbet) / (pot + bet + 5)/ (1 - compwinprob ) > 2 and\ (pot - totalcompbet) / (pot + bet + 5) > playerprobs[0]: # Computer raise restricted to 5 for hands that are not that great raisefreq = compwinprob/(1+e**(-0.1*(compamount-compthreshold))) if random() < raisefreq: if playeramount < 5: compraise(playeramount) else: compraise(5) printamounts() return 'raise' else: if lastmoves[1] == 'call':# If player calls, computer will call since it doesn't lose anything compcall() printamounts() return 'call' else: if playeraction is None: # If the computer goes first, there is nothing saved by folding. compcall() printamounts() return 'call' else: return foldorcall() else: # If mediocre hand and not bluff, there is a sensible chance of folding based on pot odds if lastmoves[1] == 'call':# If player calls, computer will call since it doesn't lose anything compcall() printamounts() return 'call' else: if playeraction is None: # If the computer goes first, there is nothing saved by folding. compcall() printamounts() return 'call' else: return foldorcall() else: # Good hand but not much money, computer will call and let the player choose to raise compcall() printamounts() return 'call' else: # If player calls, computer will call since it doesn't lose anything if playeraction is None: # If the computer goes first, there is nothing saved by folding. compcall() printamounts() return 'call' else: if lastmoves[1]=='call': # If user calls, computer can call without loosing anything compcall() printamounts() return 'call' else: # If the computer's hand is not that bad and it has enough money, it can call or fold if (1 - compwinprob )/((pot - totalcompbet) / (pot + bet)) < 1.5 and\ compamount-compthreshold > bet: return foldorcall() else: # Otherwise the computer folds compfold() printamounts() return 'fold' def printamounts(): # Print player, computer, and pot money print('You: $' + str(playeramount) + ', Computer: $' + str(compamount) + ', Pot: $' + str(pot) + '\n') # Gameplay if __name__ == '__main__': maindeck = deck() # Initialize deck discard = pile() # Initialize empty discard pile compdeck = deck() # Initialize computer's memorized deck threshold = 0.5 # Reasonable expectation of being beaten playeramount = 100 # Inital amounts compamount = 100 pot = 0 minbet = 5 bet = 0 totalplayerbet = 0 totalcompbet = 0 # For a bet to be sensible, the probability of losing must be less than this value potprob = 1 # defined as gain/(gain+loss)=(pot-total bet)/(pot + bet + raise), gain is worst case (fold) w = 5 # Controls width of sensible folding cumulative probability curve k = 2 c = 1 Xdata = [] # Stores pot probability ydata = [] # Stores associated player action (fold or no fold) memory = 100 # Number of most recent player moves to consider in logistic regression playeraction = None # Player's last action comphandsrevealed = 0 # Number of computer hands revealed compwinsrevealed = 0 # Number of computer hands revealed and won compthreshold = 25 # Threshold number of dollars before computer is less likely to raise first = 'player' # Who goes first in the round lastmoves = deque([], maxlen=2) maindeck.shuffle() print('Each player starts with $100. Minimum bet $5\n') while True: # New round procedure lastmoves.append('spaceholder') lastmoves.append('spaceholder') if maindeck.size >= 10: deal() else: maindeck = deck() discard = pile() compdeck = deck() maindeck.shuffle() deal() printamounts() if playeramount <= 0 or compamount <= 0: # If someone runs out of money upon minimum bet endround() if playeramount <= 0 or compamount <= 0: # If after comparing hands someone has no money, end game break if first != 'player': lastmoves.append(compmove()) playeraction = None if lastmoves[1] == 'fold': # If computer folds and runs out of money, the game ends if compamount <= 0: break else: # If computer folds and still has money, a new round begins endround() lastmoves.append('spaceholder') lastmoves.append('spaceholder') if maindeck.size >= 10: deal() else: maindeck = deck() discard = pile() compdeck = deck() maindeck.shuffle() deal() printamounts() if playeramount <= 0 or compamount <= 0: # If someone runs out of money upon minimum bet or raise endround() if playeramount <= 0 or compamount <= 0: # If after comparing hands someone has no money, end game break while True: # Betting rounds playermove() lastmoves.append(playeraction) if lastmoves[1] == 'fold' or (lastmoves[0] == 'call' and lastmoves[1] == 'call'): break if playeramount <= 0 or compamount <= 0: break lastmoves.append(compmove()) if lastmoves[1] == 'fold' or (lastmoves[0] == 'call' and lastmoves[1] == 'call'): break if compamount <= 0: break if lastmoves[1] == 'fold' or (lastmoves[0] == 'call' and lastmoves[1] == 'call'): endround() elif playeramount <= 0: lastmoves.append(compmove()) endround() elif compamount <= 0: playermove() lastmoves.append(playeraction) endround() if playeramount <= 0: break elif compamount <= 0: break if not lastmoves: pass elif lastmoves[1] == 'fold' or (lastmoves[0] == 'call' and lastmoves[1] == 'call'): endround() elif playeramount <= 0: lastmoves.append(compmove()) endround() elif compamount <= 0: playermove() lastmoves.append(playeraction) endround() if playeramount <= 0: print('You Lose.') elif compamount <= 0: print('You Win!')
import random a = int(input('faca sua escolha\n' '[1] pedra\n' '[2] papel\n' '[3] tesoura\n''')) lista = int(random.randint(1, 3)) #papel = 2 / pedra = 3 / tesoura = 1 PC = lista if a == 1 and PC == 1: print('Voce Venceu Pedra bate tesoura') elif a == 2 and PC == 3: print('Voce Venceu Papel engole a pedra') elif a == 3 and PC == 2: print('Voce Venceu Tesoura corta o papel') elif a == 1 and PC == 2: print('VOce perdeu Papel engole a pedra') elif a == 2 and PC == 1: print('Voce perdeu Tesoura corta o papel') elif a == 3 and PC == 3: print('Voce perdeu Pedra bate tesoura') else: print(' Ix!!! empatou jogue outra vez')
import math import csv class Point: def __init__(self, x, y): self.x = float(x) self.y = float(y) def __repr__(self): return "({},{})".format(self.x,self.y) def getx(self): return self.x def gety(self): return self.y def distance(self,pt): "a distance formula between two points" return math.sqrt( (self.getx() - pt.getx())**2 + (self.gety() - pt.gety())**2 ) class Region: """ A region represented by a list of long/lat coordinates. """ def __init__(self, coords): self.coords = coords def lats(self): "Return a list of the latitudes of all the coordinates in the region" latslist = [] for coord in self.coords: latslist.append(coord[1]) return latslist def longs(self): "Return a list of the longitudes of all the coordinates in the region" longslist = [] for coord in self.coords: longslist.append(coord[0]) return longslist def min_lat(self): "Return the minimum latitude of the region" return min(self.lats()) def min_long(self): "Return the minimum longitude of the region" return min(self.longs()) def max_lat(self): "Return the maximum latitude of the region" return max(self.lats()) def max_long(self): "Return the maximum longitude of the region" return max(self.longs()) def midpoint(self): "Return a tuple of the coordinates of the midpoint of the region" return ((self.max_long() + self.min_long())/2, (self.max_lat() + self.min_lat())/2) #http://aviationweather.gov/adds/dataserver_current/current/metars.cache.csv def temp_and_wind(self, stations): "Return a list containing the average temperature, wind speed, and wind" "direction readings from the closest 3 stations to a region's midpoint" INITIALVAL = (1000, 1000) #extremely high value used for initial comparison purposes in finding closest #stations and as a general placeholder closestations = [Point(INITIALVAL[0],INITIALVAL[1]), Point(INITIALVAL[0],INITIALVAL[1]), Point(INITIALVAL[0],INITIALVAL[1])] #list to hold 3 closest stations to a region's midpoint temps = [0,0,0] #list to hold temperature readings for 3 closest stations wind_speeds = [INITIALVAL[0],INITIALVAL[0],INITIALVAL[0]] #list to hold wind speed readings for 3 closest stations wind_directions = [INITIALVAL[0],INITIALVAL[0],INITIALVAL[0]] #list to hold wind direction readings for 3 closest stations pointmid = Point(self.midpoint()[0],self.midpoint()[1]) #midpoint of region to be used to find closest stations startindex = 0 lowerbound = 0 upperbound = len(stations)-1 midindex = int(upperbound/2) #indices used for binary search while round(float(stations[midindex][4]), 0) != round(float(pointmid.getx()), 0) and midindex>0: #binary search algorithm used to insert into list at a station with longitude #value approximately that of the midpoint of the region if round(float(stations[midindex][4]), 0) > round(float(pointmid.getx()), 0): lowerbound = midindex+1 midindex = int((lowerbound+upperbound)/2) else: upperbound =midindex-1 midindex = int((lowerbound+upperbound)/2) startindex = midindex #index of station with closest longitude value startindexsub = 50 startindexadd = 50 #values used to determine reasonable bounds of search in terms of number #of stations to increase efficiency while (startindex - startindexsub < 0): startindexsub-=1 while (startindex + startindexadd > len(stations)): startindexadd-=1 #these loops are used to avoid indexing out of bounds in determining #the search radius within the list if startindex < 1: startindexsub=0 startindexadd=len(stations)-2 #if no stations with int value longitude of the midpoint are found, the #entire list will be used in comparison for station in stations[startindex - startindexsub:startindex + startindexadd]: #for each station in the determined search radius, the station's distance from #the midpoint of the region is compared to the distances of the points already #in the closestations list. The list is always length 3; whenever a new #point is added, the point at index 0 is popped and any points at lower indices #are shifted down. The data of the new station are added to their respective #lists at the same index that the station's coordinates are added to closestations pointcur = Point(station[4], station[3]) if pointmid.distance(pointcur) < pointmid.distance(closestations[0]) and pointmid.distance(pointcur) < pointmid.distance(closestations[1]) and pointmid.distance(pointcur) < pointmid.distance(closestations[2]): #if the station is closer than all 3 points, it is appended to the list #and its corresponding data are added to their respective lists at the #same index closestations.pop(0) closestations.append(Point(pointcur.getx(),pointcur.gety())) temps.pop(0) temps.append(float(station[5])) wind_speeds.pop(0) wind_speeds.append(float(station[8])) wind_directions.pop(0) wind_directions.append(float(station[7])) elif pointmid.distance(pointcur) < pointmid.distance(closestations[0]) and pointmid.distance(pointcur) < pointmid.distance(closestations[1]): #if the station is closer than 2 of the 3 points, it is inserted at #index 1 closestations.pop(0) closestations.insert(1,Point(pointcur.getx(),pointcur.gety())) temps.pop(0) temps.insert(1,float(station[5])) wind_speeds.pop(0) wind_speeds.insert(1,float(station[8])) wind_directions.pop(0) wind_directions.insert(1,float(station[7])) elif pointmid.distance(pointcur) < pointmid.distance(closestations[0]): #if the station is closer than 1 of the 3 points, it is inserted at index 0 closestations.pop(0) closestations.insert(0,Point(pointcur.getx(),pointcur.gety())) temps.pop(0) temps.insert(0,float(station[5])) wind_speeds.pop(0) wind_speeds.insert(0,float(station[8])) wind_directions.pop(0) wind_directions.insert(0,float(station[7])) #if the station is not closer than any of the 3 points, the list remains #unchanged average_readings = [float(sum(temps)/3),float(sum(wind_speeds)/3),float(sum(wind_directions)/3)] return average_readings #temperature, wind speed, and wind direction values are averaged based on the 3 values #in their respective lists to gain a more accurate estimate of values at nearby points
def TotalScore(dice): # Sum of the score of the number of dice rolled from random import randint totalanswer=0 for z in range(0, dice) : totalanswer=totalanswer+randint(1,6) return(totalanswer) def Percent(part,whole): #The INTEGER percentage of which part (less than 100%) is of whole 100% if whole< part or part==0 or whole==0 : print ("Please enter correct values!!") whole =int(input ("Firstly the whole number : ")) part = int(input ("Then the part number to be calculated: ")) percent(part,whole) return(round(((part/whole)*100))) def DiceRolls(): # Return a histogram relative to the number of dice rolled and the score # The 'game' loops until the user exits. Data can reset each time or it can be carried over score=0 howmanydice=1 howmanytimes=1 totaltimes=0 largestscore=0 scorelist=[] percentlist=[] print ("Hello") while True : howmanydice=int(input("How many of dice would you like to roll today? (0 will quit) :" )) if howmanydice==0 : break howmanytimes=int(input("And how many times would you like to roll the dice? : ")) print() for z in range (0,howmanytimes) : score=TotalScore(howmanydice) if score>largestscore : largestscore=score totaltimes+=1 there=False for x in range (0,len(scorelist)) : if score==scorelist[x] : percentlist[x]+=1 there=True if there==False : scorelist.append(score) percentlist.append(1) for n in range (howmanydice,largestscore+1) : for y in range(0, len(scorelist)) : if n==scorelist[y] : percentage=(Percent(percentlist[y],totaltimes)) print( "%2i : %3s : %-2s" % (scorelist[y],str(percentage)+"%", percentage*"*")) print() print ("NB : 0% shows occurance, but with a large number of dice it can occur when percentage value below 1%") print() cont=input("Would you like to quit (0 or q) or try again (t)") cont=cont.upper() if cont=="0" or cont=="Q" : break else : score=0 totaltimes=0 largestscore=0 scorelist=[] percentlist=[] return()
def Percent(part,whole): #The INTEGER percentage of which part is of whole if whole< part or part==0 or whole==0 : print ("Please enter correct values!!") whole =int(input ("Firstly the whole number : ")) part = int(input ("Then the part number to be calculated: ")) Percent(part,whole) return(int(((whole-part)/whole)*100)) def TotalScore (dice): global score from random import randint score=score+Randint(1,6) TotalScore(dice-1) return(score)
def CommonTwo (string1, string2): #Uses the items from two strings and check them newstring="" if string1=="": return(string2) if string2=="": return(string1) for z in string1: for x in string2: if z==x : newstring+=z return (newstring) def CommonAll(strings): #Make a string from the duplicate items in each list item returnstring="" nowstring="" oldstring="" #Would make sense to start a loop for first list group and then compare #each list group to that # what it needs to do is go through n number of items in # list and compare them for nowstring in (strings): print ("First loop", nowstring) #x is every item in the list as we go through a loop print ("Nowstring", nowstring) print ("oldstring", oldstring) returnstring+=CommonTwo(nowstring,oldstring) print ("Returnstring :", returnstring) oldstring=nowstring return (returnstring)
contacts = {'Jason': '555-0123', 'Carl': '555-0987'} contacts['Tony'] = '555-0570' print (contacts) print ('Number of contacts', (len(contacts)))
#!/bin/python def soma(num1 ,num2): return num1+num2 #o return serve para retornar um valor e atribuir para uma outra variável x = soma(4, 5) print (x)
dict={} dict["id"]='101','102','104' dict["grade"]='A','C','E' dict["name"]='vishal','rohit','kapil' dict["section"]='D','E','F' print("enter the choice ") print("1.enter the key to see its value 2.display the whole dictionary") ch=int(input()) if(ch==1): print("enter the key") val=input() print("value is {}".format(dict[val])) elif(ch==2) : print("whole dictionary is") print(dict) else : print("wrong choice")
PI = 3.141592 raio = float(input("Digite o raio: ")) circunferencia = 2 * PI * raio a_circulo = PI * raio ** 2 a_esfera = 4 * PI * raio ** 2 vol_esfera = 4 / 3 * PI * raio ** 3 print("Circunferência: %5.6f " % (circunferencia)) print("Área do círculo: %5.6f" % (a_circulo)) print("Área da esfera: %5.6f" % (a_esfera)) print("Volume da esfera: %5.6f" % (vol_esfera))
from keras.utils import to_categorical import numpy as np #first define a dictionary of letters mapped to integer LETTERS="ABCDEFGHIJKLMNOPQRSTUWXYZV*" letter_to_int={} for i,letter in enumerate(LETTERS): letter_to_int[letter]=i #print(letter_to_int) char_to_int=dict((c,i) for i,c in enumerate(LETTERS)) int_to_char=dict((i,c) for i,c in enumerate(LETTERS)) ################################################################# #make a function that take an input of string,return the list of integer def text_to_int_converter(string): """convert a string into integer where each integer correspond to letter in string #Argument: string:letters to be converted into integer return:list containing integers """ return [char_to_int[char] for char in string] ################################################################# #make a function that take an input of integer,return the list of string def int_to_text_converter(int_list): """convert a integer list into list of character #Argument: int_list:list of integer to be converted into character return:list containing integer """ return [int_to_char[num] for num in int_list] ################################################################## #make a 27 dimensional vector for each amino acid i.e for each integer #in the list def convert_one_hot(list_integers,num_classes=27): """ convert list of integer list to numpy array """ one_hot_encod=to_categorical(s,num_classes=num_classes) np.array(one_hot_encode,type="int") return numpy_array ############################################################# # Test cases #seq="HNNIYSMFLQQTWHVQFLMLVPGEEKILHRSRVKFFGMWHNLCCSKTRTHIHQCFEQLLKYHDYRLFKDMALNRRSVQHASCDRWIRVSKMPRPVSPFRNEGSAMKPNEFCCEDAKHCTIGPKRMPDEQQFNHQQISSSACTIVFITLDVDDGHECIMAVEKTNADSTLGVNHNWCCPIWEVDDYQDDMSMRCHFKFTQQGPPWMAEMNGDYNHDPKNCCPHEYLCSAVVIWVIIEYWCYTSQGNYATICHILMNLVTEWNGFHLAIHLMMPYMVERPCKFWGAISNPCMSARFTFQPMPWSRCTTFTTVMQRDMGWLVGQRMMPMMSIGWASCMWWPVVQSPGFHFQMFCTTNSQFHRTLNHTNQSICQIMTWRGDPEYDYPNAMCTWKKQKRRKGWGQLHNMPQEPPYQANYSYNGRCVDHVIHQQVVVVGMVFRMELLLFLCDKGWEEECVCNANNGPLRQGFSYEWVCWAWKLDNSGFTVFGTPFFGDHPIGYLCTIHSETNYSYTVHHPSQVRKEVRFNYWKGHENNHTRRSHIQMLCDVVCHFTFGSLMRRLCPCRWPPRDYCIRQDHPWCIYGMPTKQDKDAKLWDTYHPYSWLELEDCYLFCPFSRVFDQKLIMAHIVRICHTCLQMRMQSLMYIMYNSHGLCIIGRDSRWAHKRRYFGSDMPSCYHYLSFHFVRDLNDVRCGVDCDGLSNRFGLNDLNKLTHHNCKKNNGMILAVNSTTCEPKPTHQFAHVWSIIKHNNESVWNGLSGPEFAKQTCFSDGFFDPFMQWDHKPRFPRMCVQNHNDHLYQIYCRGTDEREQVAMESHFEFEQSNEKCVQQDVQEARSGTWHEGNEADVFPINEMRTHKCEGQNVNLQFSCCERQSAIMNCEAIRCATWKFTECVITQDCNWRRWRSYDLQYLQWGHYPKQEFMCFTDGQNDSPTVFNVEIKGK" seq="HNNIYSMFLQQ" s=text_to_int_converter(seq) print(s) #list_num=[3,4,5] #d=int_to_text_converter(s) #print(d) print("""""") print("""""") print("--------------------------------------------------") a=to_categorical(s,num_classes=27) print(a) print(a.shape) #one_h=one_hot(d,20) #printtone_h) ###def one_hot_encode(protein_integered): ## """ ## ## #one hot encoding of protein sequence ## ## #Argument: ## #protein_integered:protein sequence represented by integerlist ## ## #output ## #one hot encoded 2D array of size(no of residue,20) ## ## """ #make a 2D array of float32 whose no of rows equal to no of residue # of amino acid and columun is 20 ## no_aminoacid=len(s) ## repre=np.zeros(no_aminoacid,dtype=float) ## for digit in protein_integered: ## l=np.zeros((1,20),dtype=float) ## l[repre]=1 ## repre.add #using one_hot from keras convert it into input array
# Line towards your cursor with infinite length # Right Click or Left Click to change position # By: Ali import pygame # --- constants --- BLACK = (0, 0, 0) GREEN = (0, 255, 0) DISPLAY_WIDTH = 800 DISPLAY_HEIGHT = 600 # --- functions --- def calculate(player_x, player_y, mouse_x, mouse_y): dx = player_x - mouse_x + 0.1 dy = player_y - mouse_y reversed_sign_x = 1 if dx < 0 else -1 #reversed_sign_y = 1 if dy < 0 else -1 slope = dy/dx x_new = reversed_sign_x * DISPLAY_WIDTH y_new = player_y + slope * (x_new - player_x) return x_new, y_new # --- main --- # - init - pygame.init() SCREEN = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT)) # - objects - player_x = DISPLAY_WIDTH // 2 player_y = DISPLAY_HEIGHT // 2 mouse_x = player_x mouse_y = player_y x_new, y_new = calculate(player_x, player_y, mouse_x, mouse_y) # - mainloop - clock = pygame.time.Clock() running = True while running: # - events - for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN: player_x, player_y = event.pos elif event.type == pygame.MOUSEMOTION: x_new, y_new = calculate(player_x, player_y, event.pos[0], event.pos[1]) # - updates - # empty # - draws - SCREEN.fill(BLACK) pygame.draw.line(SCREEN, GREEN, (player_x, player_y), (x_new, y_new), 2) pygame.display.flip() # - FPS - clock.tick(25) # - end - pygame.quit()
#is power of 2 def is_power_of_two(x): return x&(x-1)==0 #最大公约数 def gcd(a,b): # O(logmax(a,b)) if b==0: return a return gcd(b,a%b) # 求x,y 使得 ax+by=gcd(a,b) d=gcd(a,b) def extgcd(a,b,d): if b==0: return d/a,1 x,y=extgcd(b,a%b) return y,x-int(a/b)*y #最大公约数 def gcd(a,b): # O(logmax(a,b)) if b==0: return a return gcd(b,a%b) #最小公倍数 least common multiple def lcm(a,b): return a*b//gcd(a,b) def lcm(args): ret=lcm(args[0],args[1]) for num in args[2:]: ret=lcm(ret,num) return ret # 最小互质 #relative primes def rg(a,b): g = abs(gcd(a,b)) assert g return a // g, b // g #判定prime number def is_prime(n): i=2 while i*i<=n: if n%i==0: return False i+=1 return n!=1 def divisor(n): res=[] i=1 while i*i<=n: if n%i==0: res.append(i) if i!=n/i: res.append(n/i) i+=1 return res def prime_factor(n): res=[] i=2 while i*i<=n: while n%i==0: res.append(i) n/=i i+=1 if n!=1: res.append(n) return res # Sieve of Eratosthenes # 枚举n 以内素数 包括n # O(nloglogn) ~ O(n) def sieve(n): is_prime=[True]*(n+1) is_prime[0]=False is_prime[1]=False limit=int(n**0.5)+1 for i in range(2,limit): if is_prime[i]: j=2*i while j<=n: is_prime[j]=False j+=i return [i for i,val in enumerate(is_prime) if val] # 枚举 [a,b) 内素数 def segment_sieve(a,b): limit=int(b**0.5) prime_small=sieve(limit) is_prime=[True]*(b-a) for i in prime_small: j=math.ceil(a/i)*i while j<b: is_prime[j-a]=False j+=i return [i+a for i,val in enumerate(is_prime) if val] # is carmicheal number # find pow(x,y) under given modulo mod def is_prime(n): i=2 while i*i<=n: if n%i==0: return False i+=1 return n!=1 def gcd(a,b): # O(logmax(a,b)) if b==0: return a return gcd(b,a%b) def power_mod(x,y,mod): if y==0: return 1 res=power_mod(x*x%mod,int(y/2),mod) if y%2==1: res=(res*x)%mod return res def is_carmicheal_number(n): if is_prime(n) or n==1: return False for x in range(2,n): if gcd(x,n)==1: if power_mod(x,n-1,n)!=1: return False return True
#!/usr/bin/env python #from sys.stdout import write import sys import StringIO class Board: BLANK = ' ' BORDER_HOR = '-------------\n' BORDER_VER = '|' WIDTH = 9 HEIGHT = 9 def __init__(self, board=[]): self.board = board if not board: B = self.BLANK self.board = [[B, 4, B, B, B, 5, B, 1, B], [B, B, B, B, 1, B, 6, B, 9], [6, B, 1, 9, 3, B, B, B, 4], [5, B, 2, 6, 9, B, B, 7, B], [B, 3, B, 7, B, 1, B, 9, B], [B, 9, B, B, 4, 8, 1, B, 5], [1, B, B, B, 7, 9, 8, B, 2], [9, B, 3, B, 8, B, B, B, B], [B, 7, B, 1, B, B, B, 4, B]] def __str__(self): s = StringIO.StringIO() for i in range(self.HEIGHT): if i == 0: s.write(self.BORDER_HOR) for j in range(self.WIDTH): if j == 0: s.write(self.BORDER_VER) s.write(str(self.board[i][j])) if j % 3 == 2: s.write(self.BORDER_VER) s.write('\n') if i % 3 == 2: s.write(self.BORDER_HOR) return s.getvalue() def solve_init(board): solve(0, 0, board) def solve(row, col, board): # are we finished if row == board.HEIGHT: row = 0 col += 1 if col == board.WIDTH: return True # skip if we're on a filled spot if board.board[row][col] != board.BLANK: return solve(row+1, col, board) # try solutions until we've got one (1-9 are only choices) for val in range(1, 10): if ok_placement(row, col, board, val): board.board[row][col] = val if solve(row+1, col, board): return True # Back track if no solution is found board.board[row][col] = board.BLANK return False def ok_placement(row, col, board, attempt): # check row for check in range(board.WIDTH): if attempt == board.board[check][col]: return False # check column for check in range(board.HEIGHT): if attempt == board.board[row][check]: return False xBox = row / 3 * 3 yBox = col / 3 * 3 for x in range(3): for y in range(3): if attempt == board.board[(xBox+x)][(yBox+y)]: return False return True if __name__ == "__main__": b = Board() print "Before solution:" print b solve_init(b) print "Solution:" print b
""" Compute mean square displacement date: 06/21/2017 """ import numpy from numpy import ndarray def msd(x: ndarray) -> ndarray: """Assume each row is for one atom""" N = x.shape[0] def aux(gap: int) -> float: return numpy.average( numpy.sum( numpy.square(x[gap:N, :] - x[0:N-gap, :]), axis=1 ) ) return numpy.array([aux(i) for i in range(1, N)])
import sys import pygame from random import randint #setting the dimensions of screen,bricks,paddle,and the ball Screen_size = 800, 600 Brick_width =65 Brick_height = 20 Paddle_width = 200 Paddle_height = 20 Ball_diameter = 25 Ball_radius = int(Ball_diameter / 2) PADDLEX = Screen_size[0] - Paddle_width BALLX = Screen_size[0] - Ball_diameter BALLY = Screen_size[1] - Ball_diameter PADDLEY = Screen_size[1] - Paddle_height - 10 #setting colors Black = (0, 0, 0) White = (255, 255, 255) Blue=(11,7,116) Grey = (102, 92, 94) Red = (255,0,0) #setting the states start = 0 playing = 1 won = 2 game_over = 3 class Brick: def __init__(self): pygame.init() #initiallizing the size of the screen,the caption and its font self.screen = pygame.display.set_mode(Screen_size) pygame.display.set_caption("Breakout game") self.clock = pygame.time.Clock() self.font = pygame.font.Font(None, 30) self.game() def game(self): self.lives = 3 self.score = 0 self.state = start #setting the position and dimensions of the paddle and the ball self.paddle = pygame.Rect(300, PADDLEY, Paddle_width, Paddle_height) self.ball = pygame.Rect(100, PADDLEY - Ball_diameter, Ball_diameter, Ball_diameter) #initiallizing the velocity of the ball self.ball_vel = [5, -5] self.bricks() def bricks(self): #creating the bricks(5 rows with 10 brick in each row) m = 60 self.bricks = [] for i in range(5): l = 35 for j in range(10): self.bricks.append(pygame.Rect(l, m, Brick_width, Brick_height)) l += Brick_width + 10 m += Brick_height + 5 def drawbricks(self): #setting the bricks on the screen with their color and shape for brick in self.bricks: pygame.draw.rect(self.screen, Blue, brick) def Event(self): #checking the event fired by the user depending on the pressed key(left key,right key,enter or space) keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.paddle.left -= 5 if self.paddle.left < 0: self.paddle.left = 0 if keys[pygame.K_RIGHT]: self.paddle.left += 5 if self.paddle.left > PADDLEX: self.paddle.left = PADDLEX if keys[pygame.K_SPACE] and self.state == start: self.ball_vel = [randint(5, 8),randint(5, 8)] self.state = playing elif keys[pygame.K_RETURN] and (self.state == game_over or self.state == won): self.init_game() def Ballmovement(self): #controlling the movement of the ball self.ball.left += self.ball_vel[0] self.ball.top += self.ball_vel[1] if self.ball.left <= 0: self.ball.left = 0 self.ball_vel[0] = -self.ball_vel[0] elif self.ball.left >= BALLX: self.ball.left = BALLX self.ball_vel[0] = -self.ball_vel[0] if self.ball.top < 0: self.ball.top = 0 self.ball_vel[1] = -self.ball_vel[1] elif self.ball.top >= BALLY: self.ball.top = BALLY self.ball_vel[1] = -self.ball_vel[1] def Collision(self): #changing the score,lives and the state when the ball hits the brick for brick in self.bricks: if self.ball.colliderect(brick): self.score += 1 #if the ball hits the brick,increase the score by one and remove this brick self.ball_vel[1] = -self.ball_vel[1] pygame.draw.rect(self.screen, Red, brick) self.bricks.remove(brick) break if len(self.bricks) == 0: self.state = won if self.ball.colliderect(self.paddle): self.ball.top = PADDLEY - Ball_diameter self.ball_vel[1] = -self.ball_vel[1] elif self.ball.top > self.paddle.top:#if the ball hits the ground,decrease the lives by 1 self.lives -= 1 if self.lives > 0: self.state = start else: #if lives=0 ,ends the game self.state = game_over def Stats(self):#showing the score and the lives on the screen pygame.draw.line(self.screen, White, [0, 30], [800, 30], 2) text = self.font.render("Score: " + str(self.score), 1, White) self.screen.blit(text, (20, 10)) text = self.font.render("Lives: " + str(self.lives), 1, White) self.screen.blit(text, (700, 10)) def message(self, message):#determine the position and the color of the showed message if self.font: size = self.font.size(message) font_surface = self.font.render(message, False, White) x = (Screen_size[0] - size[0]) / 2 y = (Screen_size[1] - size[1]) / 2 self.screen.blit(font_surface, (x, y)) def run(self): while 1: for event in pygame.event.get(): if event.type == pygame.QUIT:#if the user press quit,exit the game sys.exit() self.clock.tick(50) self.screen.fill(Grey) #background of the screen self.Event() #determine which message to be appeared according to the state of the gaem if self.state == playing: self.Ballmovement() self.Collision() elif self.state == start: self.ball.left = self.paddle.left + self.paddle.width / 2 self.ball.top = self.paddle.top - self.ball.height self.message("PRESS SPACE TO START THE GAME") elif self.state == game_over: self.message("GAME OVER!! PRESS ENTER TO PLAY AGAIN") text2 = self.font.render('your score is '+str(self.score),1, White ) self.screen.blit(text2, (350, 250)) elif self.state == won: self.message("YOU WON!! PRESS ENTER TO PLAY AGAIN") text2 = self.font.render('your score is ' + str(self.score), 1, White) self.screen.blit(text2, (350, 250)) self.drawbricks() #display the paddle and the ball on the screen pygame.draw.rect(self.screen, Black, self.paddle) pygame.draw.circle(self.screen, White, (self.ball.left + Ball_radius, self.ball.top + Ball_radius), Ball_radius) self.Stats() pygame.display.flip() if __name__ == "__main__": Brick().run()
def INT(): return int(input()) def MAP(): return map(int, input().split()) X = INT() year = 0 cash = 100 while cash < X: year += 1 cash = int(cash * 1.01) print(year)
import math H = int(input()) if H == 1: print(1) exit() n = int(math.log2(H)) #print(n) print(2**(n+1)-1)
class Solution: """ Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height. Time: 93% (28ms) O(nlogn) """ def heightChecker(self, heights: List[int]) -> int: sorted_heights = sorted(heights) count = 0 i = 0 while i < len(heights): if heights[i] != sorted_heights[i]: count += 1 i += 1 return count
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None import heapq class Solution: def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: """ Construct a maximum binary tree from an array of integers """ if nums == []: return max_val = max(nums) index = nums.index(max_val) root = TreeNode(max_val) root.left = self.constructMaximumBinaryTree(nums[:index]) root.right = self.constructMaximumBinaryTree(nums[index + 1:]) return root
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return level_q = [] waiting_q = [] result = [] result.append([root.val]) level_q.append(root.left) level_q.append(root.right) while level_q: curr = [] while level_q: tmp = level_q.pop(0) if tmp is None: continue curr.append(tmp.val) waiting_q.append(tmp) if len(curr) != 0: result.append(curr) while waiting_q: tmp = waiting_q.pop(0) if tmp.left is not None: level_q.append(tmp.left) if tmp.right is not None: level_q.append(tmp.right) return result
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: def construct_tree(left, right): nonlocal post_index if left == right: return None root_val = postorder[post_index] root = TreeNode(root_val) index = index_map[root_val] post_index -= 1 root.right = construct_tree(index + 1, right) root.left = construct_tree(left, index) return root post_index = len(postorder) - 1 index_map = {val:index for index,val in enumerate(inorder)} return construct_tree(0,len(inorder))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def smallestFromLeaf(self, root: TreeNode) -> str: self.strings = [] self.char_map = {} alph = "abcdefghijklmnopqrstuvwxyz" for i in range(len(alph)): self.char_map[i] = alph[i] self.dfs(root,"") return ''.join(min(self.strings)) def dfs(self, node, string): if not node.left and not node.right: self.strings.append(list(reversed(string + self.char_map[node.val]))) else: if node.left: self.dfs(node.left,string + self.char_map[node.val]) if node.right: self.dfs(node.right, string + self.char_map[node.val])
class Solution: """ Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. Time: 77%-94% (72ms - 80ms) """ def sortArrayByParity(self, A: List[int]) -> List[int]: evens = [] odds = [] for n in A: if n % 2 == 0: evens.append(n) else: odds.append(n) return evens + odds
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def rightSideView(self, root: TreeNode) -> List[int]: # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution: def rightSideView(self, root: TreeNode) -> List[int]: if not root: return [] result = [] level = deque() waiting = deque() level.append(root) while level: added = False while level: temp = level.popleft() if not added: result.append(temp.val) added = True waiting.append(temp) while waiting: temp = waiting.popleft() if temp.right is not None: level.append(temp.right) if temp.left is not None: level.append(temp.left) return result
def make_pizza(size,*args): """Summarize the pizza we are about to make""" print(f"\nMaking a {size}-inch pizza with the following toppings:") for arg in args: print(f"+ {arg}")
# Store information about a person in a dictionary, first name, last name, age and city. Then # print call it's key and print the value inside it. person = { 'first_name': 'Bianca', 'last_name': 'Pal', 'age': 21, 'city': 'Lleida' } print(person['first_name']) print(person['last_name']) print(person['age']) print(person['city']) # Use a dictionary to store people's favorite numbers. Think of five names, and store them as # keys in your dictionary. Then print each person's name and their favorite number. favorite_numbers = { 'Bianca': 16, 'Alex': 11, 'Naomi': 4, 'Tira': 8, 'Loe': 7, } print(f"Bianca's favorite number is {favorite_numbers['Bianca']}") print(f"Alex's favorite number is {favorite_numbers['Alex']}") print(f"Naomi's favorite number is {favorite_numbers['Naomi']}") print(f"Tira's favorite number is {favorite_numbers['Tira']}") print(f"Loe's favorite number is {favorite_numbers['Loe']}") # Think of five programming words you've learned about in the previous chapters. Use these # words as the keys in your glossary, and store their meanings as values. # Print each word and its meaning as neatly formatted output. You might print the word followed # by a colon and then it's meaning, or print the word on one line and then print its meaning # indented on a second line. Use the newline character (\n) to insert a blank line between each # word-meaning pair in your output. programming_words = { 'for': 'programming structure that repeats a sequence of instructions until a specific condition is met', 'indentation': 'refers to the spaces at the beginning of a code line that indicate a block of code', 'comprehension': 'define and create lists based on existing lists', 'elif': 'the second condition in an if-elif-else conditional structure', 'tabs': 'Fixed horizontal distance ranged between 4 and 8 spaces long', } print(f"\nfor:{programming_words['for']}") print(f"\nindentation:{programming_words['indentation']}") print(f"\ncomprehension:{programming_words['comprehension']}") print(f"\nelif:{programming_words['elif']}") print(f"\ntabs:{programming_words['tabs']}")
# PASSING ARGUMENTS # Positional arguments # When you call a function, Python must match each argument in the function call with a # parameter in the function definition. The simplest way to do this is based on the order # of the arguments provided. Values matched up this way are called positional arguments. def describe_pet(animal_type, pet_name): """Display information about a pet""" print(f"\nI have a {animal_type}.") print(f"\nMy {animal_type}'s name is {pet_name.title()}.") describe_pet('hamster','Messi') # The order of the arguments have to match the exact order of the parameters. # MULTIPLE FUNCTION CALLS describe_pet('parrot', 'ciupy') describe_pet('fish','goldie') # You can use as many positional arguments as you need in your functions. Python works # through the arguments you provide when calling the function and matches each one with # the corresponding parameter in the function's definition. # Order matters in Positional Arguments: you can get unexpected results if you mix the # order of the arguments. # KEYWORD ARGUMENTS # A keyword argument is a name-value pair that you pass to a function. You directly # associate the name and the value within the argument, so when you pass the argument # to the function, there's no confusion. def describe_pet_rewritten(animal_type, pet_name): """Display information about your pet""" print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}.'") describe_pet_rewritten(animal_type='hamster', pet_name='harry') # DEFAULT VALUES # When writting a function, you can define a default value for each parameter. If an # argument for a parameter is provided in the function call, Python uses the argument # value. If not, it uses the parameter's default value. So when you define a default # value for a parameter, you can exclude the corresponding argument you'd usually write # in the function call. def describe_pet_default(pet_name, animal_type='dog'): """Display information about your pet""" print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet_default(pet_name='lola') # Non-default argument follows default argument. This happens because Python still interprets # this as a positional argument, so if the function is called with just a pet's name, that # argument will match up with the first parameter listed in the function's definition. # To describe an animal other than dog, you could use a function call like this. describe_pet_default(pet_name='jiji',animal_type='turtle') # When you use default values, any parameter with a default value needs to be listed after # all the parameters that don't have default values. This allows Python to continue interpreting # positional arguments correctly. # All the following calls would work for this function. describe_pet_default('willie') describe_pet_default(pet_name='willie') describe_pet_default('harry','hamster') describe_pet_default(pet_name='harry', animal_type='hamster') describe_pet_default(animal_type='hamster', pet_name='harry') # If you don't want to write the keywords, you must define each argument in the same orther # as the parameters. You can switch the order of the arguments if you include the keywords. # AVOIDING ARGUMENT ERRORS # If you try to call a function with no arguments, you'll get an error. Python will tell you # which are the missing arguments. Also if you provide to many arguments you should get a # simmilar traceback.
#"Gabriel Garcia Marquez, part of poem" print("If for a moment God would forget that I am a rag doll and give me a scrap of life, possibly I would not say everything that I think, but I would definitely think everything that I say.") print("I would value things not for how much they are worth but rather for what they mean.") print("I would sleep little, dream more. I know that for each minute that we close our eyes we lose sixty seconds of light.") print("I would walk when the others loiter; I would awaken when the others sleep.") print("I would listen when the others speak, and how I would enjoy a good chocolate ice cream.") print("If God would bestow on me a scrap of life, I would dress simply, I would throw myself flat under the sun, exposing not only my body but also my soul.")
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] for requested_topping in requested_toppings: print(f"Adding {requested_topping}.") print("\nFinished making your pizza\n") # An if statement in the loop could handle the possibility that there isn't # any element left for requested_topping in requested_toppings: if requested_topping == 'green peppers': print(f"Sorry, we are out of {requested_topping} right now") else: print(f"Adding {requested_topping}.") print("\nFinished making your pizza") # CHECKING THAT A LIST IS NOT EMPTY # Soon we'll let users provide the information that's sorted in a list, so we # won't be able to assume that a list has any items in it each time a loop is run. # In this situation, it's useful to check whether a list is empty before running a # for loop. requested_toppings = [] if requested_toppings: for requested_topping in requested_toppings: print(f"Adding {requested_topping} .") print("\nFinished making your pizza") else: print("Are you sure you want a plain pizza") # When the name of a list is used in an if statement, Python returns True if the # list contains at least one item; an empty evaluates to False. tipe = '' # TERNARY IN VARIABLE print("Tiene tipo") if tipe else print("No tiene tipo\n") # USING MULTIPLE LISTS ( TOPPING REQUESTS FROM AVAILABLE TOPPINGS) available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print(f"Adding {requested_topping}.") else: print(f"Sorry, we don't have {requested_topping}.") print("\nFinished making your pizza") # We loop through the list of requested toppings, but in there we check to see if each requested topping # is actually in the list of available toppings. If it is we add the topping to the pizza else we print # that the particular topping which didn't match inside the available toppings is not available.
guests = ['Guaynaa', 'Katy Perry', 'Orlando Bloom', 'Maluma', 'Miley Cyrus'] for guest in range(0,5): print(f"Would you want to come to dinner with me {guests[guest]}") print('\n') not_arriving = guests.pop() new_guest = guests.append('Fuego') for guest in range(0,5): print(f"Would you want to come to dinner with me {guests[guest]}") for guest in range(0,5): print(f"I found a bigger table {guests[guest]}") guests.insert(0,'Inna') guests.insert(3,'Farina') guests.append('Tangana') for guest in range(0,8): print(f"Would you want to come to dinner with me {guests[guest]}") for guest in range(0,8): print(f"I only can invite two people at dinner with me {guests[guest]}") uninvited = [] for guest in range(0,6): lel=guests.pop() uninvited.append(lel) print(f"Sorry you are uninvited {lel}") print(guests) print(uninvited) for guest in range(0,2): print(f"You are still invited {guests[guest]}") for guest in range(0,2): del guests[guest] print(guests)
# Hacer un programa que sume con un bucle los cuadrados de los números del 1 al n # pidiendo al usuario el valor de n. Después de hacerlo, comprobar que coincide con: # (n(n + 1)(2n + 1))/6 # Se puede imprimir el resultado de esta ecuación y después el resultado de nuestra # suma. numero = int(input("Introduce un numero:")) suma = 0 for i in range(1,numero+1): cuadrado = i**2 suma += cuadrado funcion = (numero*(numero+1)*(2*numero + 1))/6 if suma == funcion: print("Coincide") else: print("No coincide")
# + plus # - minus # / devide # * times # ** exponentiation # % modulo # < less than # > greater than print ("What is the answer to life, the universe, and everything?", int((40 + 30 - 7) * 2 / 3)) print ("Is it true that 5 * 2 > 3 * 4?") print (5 * 2 > 3 * 4) print("What is 5 * 2?", 5 * 2) print("What is 3 * 4?", 3 * 4)
# Write a function that accepts a list of items a person wants on a sandwich. The function # should have one parameter that collects as many items as the function call, provides, and # it should print a summary of the sandwich that's being ordered. Call the function three # times, using a different number of arguments each time. def make_sandwich(*ingredients): for ingredient in ingredients: print(f"We're adding {ingredient}") print("Your sandwhich is ready for pickup") make_sandwich('cheese','olives','fuet') make_sandwich('tortilla') make_sandwich('cherry tomatoe','oil') # Build a profile of yourself by calling build_profile(), using your first and last names and # three other key-value pairs that describe you. def build_profile(first, last, **kwargs): kwargs['first_name'] = first kwargs['last_name'] = last return kwargs user_1 = build_profile('Bianca','Pal',age=21,country='Spain') print(user_1) # Write a function that stores information about a car in a dictionary. The function should # always receive a manufacturer and a model name. It should then accept an arbitrary number # of keyword arguments. Call the function with the required information and two other name-value # pairs, such as a color or an optional feature. Your function should work for a call like # this one. def make_car(manufacturer,model_name,**kwargs): kwargs['manufacturer'] = manufacturer kwargs['model_name'] = model_name return kwargs model_1 = make_car('subaru','outback',color='blue',tow_package=True) print(model_1)
# TUPLE # A Tuple is a inmutable list # It looks like a list except you use parenthesis instead of squared brackets. Once you define a tuple, you can access individual elements by using each item's index, just as you would for a list dimensions = (200, 50) print(dimensions[0]) print(dimensions[1]) # If you try to change the value of one index you will get 'tuple' object does not support item assignment # If you want to define a tuple with only just one element you need to defined by the presence of a comma. my_t = (3,) print(my_t[0]) # LOOPING THROUGH ALL VALUES OF A TUPLE for dimension in dimensions: print(dimension) # WRITING OVER A TUPLE # Although you can't modify a tuple, you can assign a new value to a variable that represents a tuple. So if we wanted to change our dimensions, we could redefine the entire tuple: print("Original dimensions") for dimension in dimensions: print(dimension) # Changing the values it's not possible but yes reassigning a variable is valid. dimensions = (400, 100) print("Modified dimensions") for dimension in dimensions: print(dimension)
name = "ada lovelace" # this method changes each word to title case, where each word begins with a capital letter. print(name.title()) # this method changes a string to uppercase print(name.upper()) # this method changes a string to lowercase print(name.lower())
import os os.system('clear') total_amount = float(input("How much is the total amount? ").strip('$')) tip_15 = total_amount*0.15 tip_18 = total_amount*0.18 tip_20 = total_amount*0.20 print (f"A 15% tip would be an amount of ${tip_15:.2f}") print (f"A 18% tip would be an amount of ${tip_18:.2f}") print (f"A 20% tip would be an amount of ${tip_20:.2f}")
# Pedir al usuario una cantidad en euros (real) y componer esa cantidad mediante # la mínima variedad de billetes y monedas. Para ello pasar primero la cantidad dada # en euros a céntimos: def centimos(euros): cents = int(euros) cents = (round(cents*100)) factor_conversion = { 'C500': [50000] , 'C200': [20000] , 'C100': [10000] , 'C50': [5000 ], 'C20': [2000 ], 'C10': [1000 ], 'C5': [500] , 'C2': [200] , 'C1': [100] , 'C050': [50] , 'C020': [20] , 'C010': [10] , 'C005': [5 ], 'C002': [2 ], 'C001': [1 ], } numero_billetes_por_billete = {} for key,value in factor_conversion.items(): for numero in value: if cents >= numero: numero_billetes = cents // numero numero_billetes_por_billete.update({key:numero_billetes}) cents_convertidos = numero * numero_billetes cents = cents - cents_convertidos else: numero_billetes_por_billete.update({key:0}) print(numero_billetes_por_billete) euros= input("Dime los euros: ") centimos(euros)
# Repetir el programa anterior pero para dibujar cualquier polígono de lado 50. Para ello # declaramos una variable nlados=6 (por ejemplo) antes y después repetimos (for) el dibujo del # lado, y giramos el ánguloExt = 360/nlados, o sea, right(360/nlados). import turtle s = turtle.getscreen() for i in range(1,6): turtle.forward(50) turtle.left(72)
import random def removeTheVowelsImp(inputString): vowels = ["a", "i", "e", "o", "u"] theConsonants = "".join([x for x in inputString if x not in vowels]) return theConsonants test = removeTheVowelsImp("This is a Test String") print(test) print(" ") vowels = ["a", "i", "e", "o", "u"] weekDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Firday"] noVowels = ["".join([x for x in d if x not in vowels]) for d in weekDays] print(noVowels) print(" ") numbers = [11, -17, 42, 8, -12, 9] onlypostive = [x if x > 0 else 0 for x in numbers] print(onlypostive) print(" ") class FlashCards: def __init__(self, InputList): self.wordList = InputList def __iter__(self): return self def __next__(self): wordNum = len(self.wordList) - 1 ranWord = random.randint(0, wordNum) currentWord = self.wordList[ranWord] return currentWord germanWords = FlashCards(["die kuh", "der hund", "die katze", "das Pferd", "die Ente"]) for i in range(5): print(next(germanWords)) print(" ") def listReverser(inputStringList): inputStringList.reverse() for x in inputStringList: yield x g = listReverser(["antelope", "burro", "cheetah", "donkey", "elephant"]) for w in g: print(w) print(" ") qt = listReverser(["antelope", "burro", "cheetah", "donkey", "elephant"]) sevenOrMore = [w for w in qt if len(w) >= 7] print(sevenOrMore)