text
stringlengths
37
1.41M
import matplotlib.pyplot as plt import numpy as np from math import sin, cos, radians,sqrt import Tools #______Coordenadas iniciales xg=[] yg=[] zg=[] #Cordenadas centrales xc=40 yc=40 zc=60 #Plano y linea de sistema x=[40,30,80] y=[0,0,0,0] z=[60,10,60] ####_____pedir al usaurio que eje desea...
#Lists fruits = ['apple', 'banana', 'orange', 'strawberry'] vegetables = ['lettuce', 'cucumber', 'carrots'] fruits_and_vegetables = fruits + vegetables print fruits_and_vegetables salad = 3 * vegetables print salad print fruits[0] fruits.append('blueberry') print fruits my_list = [1, 'Zen', 'hi'] print len(my_...
print ("Hello World!") name = "Zen" x= 43 print "My name is", x name = "Zen" # you can only concatenate the same data types --print "My name is " + x print "this is a sample string" print name.upper()
# Include Pandas and set up the file setup import pandas as pd import numpy as np census_df = pd.read_csv('census.csv') # Question 7 - Which county has had the largest absolute change in population within the period 2010-2015? # Select 2010-2015 population columns and keep only the county records (i.e. elimina...
n=input("Enter the number of which you want a table till 100 value as max: ") i=1 t=0 while t<=100: print(t) t=int(n)*i i+=1
Alfa = int(input()) Onser = Alfa Dec = 10 F = 0 Y = 0 mem = Alfa if Alfa == 1: print(1) elif Alfa == 0: print(1) else: while True: mem = mem * Alfa F = mem % 10 + Y Onser = Onser + Dec * (F % 10) Dec = Dec*10 Y = int((mem / 10) % 10)+int((F/10)) mem = int(F % 1...
from guitar import Guitar guitars = [] print("My Guitars!") name = input("Name: ") while name != "": year = int(input("Year: ")) cost = float(input("Cost: ")) print("{} ({}) : ${:.2f} added.".format(name, year, cost)) new_guitar = Guitar(name, year, cost) guitars.append(new_guitar) name = input...
# 1.6 String Compression: Implement a method to perform basic string # compression using the counts of repeated characters. # For example, the string aabcccccaaa would become a2b1c5a3. # If the "compressed"string would not become smaller than the # original string, your method should return the original string. # ...
# Partition: Write code to partition a linked list around a value x, # such that all nodes less than x come before all nodes greater than # or equal to x. If x is contained within the list, the values of x # only need to be after the elements less than x (see below). # The partition element x can appear anywhere in...
# 1.7 Rotate Matrix: Given an image represented 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? def rotate90(matrix): new_matrix = [] for M in range(len(matrix)): row = [] for N in range (len(matrix[M])): # row.appe...
#1.4 Given a string, write a function to check if it is a permutation of a palin- drome. # A palindrome is a word or phrase that is the same forwards and backwards. # A permutation is a rearrangement of letters.The palindrome does not need to be limited to just dictionary words. def isPalondrome(str1, str2): if len...
""" Stores script state A script can choose to use states rather than an evaluation method, the script state gets set during the script runtime Each state has a default status and message, these can be overwritten elsewhere if a custom status or message is needed """ class StateAssertException(Exception): pass ...
numero = int(input('Digite um numero: ')) print('O numero {} tem o Antecessor {} e Sucessor {}'.format(numero, numero - 1, numero + 1))
dias = float(input('Por quantos dia você alugou o Carro: ')) km = float(input('Quandos Km você andou: ')) carro = dias * 60 kmRodado = km * 0.15 total = float(carro + kmRodado) print('O preço total a ser pagado é de R${}'.format(total))
class TreeNode: def __init__(self, key, val): self.key = key self.value = val self._left_child = None self._right_child = None self.parent = None @property def left_child(self): return self._left_child @left_child.setter def left_child(self, node): ...
# 합병 정렬 def merge_sort(list): if len(list) <= 1: return list mid = len(list) // 2 left_list = list[:mid] right_list = list[mid:] left_list = merge_sort(left_list) right_list = merge_sort(right_list) return merge(left_list, right_list) def merge(left_list, right_list): resul...
# radix sort # queue_list = [list() for _ in range(10)] # # print(queue_list) def radix_sort(ordered_list): is_sorted = False position = 1 while not is_sorted: is_sorted = True queue_list = [list() for _ in range(10)] for num in ordered_list: digit_number = (int)(num ...
# -*- coding: utf-8 -*- __author__ = "Luca Mella" __version__ = "$Revision: 0.1 $" __date__ = "$Date: 2013/05/20 $" __copyright__ = "Copyright (c) 2012-2013 Luca Mella" __license__ = "CC BY-NC-SA" """ MATHEMATICAL MORPHOLOGY All the routines must work with logical (B/W) and greyscale images, with automatic detec...
# ################################################### metodos python ######################################################### nombre = "aDrIaN" # pone los nombre minusculas nombre = nombre.lower() # pone los nombre en m mayuscula nombre = nombre.upper() # cuanta cuantas vese esta la "a" en adrian nombre.count("a") pri...
########################################################condicionales notas=int(input("dijite su nota: ")) def evaluacion(notas): valoracion="aprobado" if notas < 5: valoracion="no,aprobado" return valoracion print(evaluacion(notas)) #######utilizando in para ver que si crelegida esta en careras ...
class NodoArbol: def __init__( self , value , left= None, right=None): self.data = value self.left = left self.right = right class BinarySearchTree: def __init__( self ): self.__root = None def insert( self , value ): #regla 1 if self.__root ==...
def plot_histogram(a): for i in a: print('* '*i) plot = [2,3,6,5] plot1 = [1,3,2,4,6,5,7,8,9,2,1,3] plot_histogram(plot) print('---------------------------') plot_histogram(plot1)
def binary_search(list, n): l = 0 u = len(list) - 1 while l <= u: mid = (l + u) // 2 if list[mid] == n: return True else: if list[mid] < n: l = mid+1 else: u = mid+1 return False list = [5,7,44,6,8,9] x = int...
s = input() if len(s) < 5: print("No") elif s[0] == "M" and s[1] == "U" and s[2] == "J" and s[3] == "I" and s[4] == "N": print("Yes") else: print("No")
n = int(input()) ans = 0 for a in range(10 ** 5): if a ** 2 <= n: ans = a else: break print(ans)
s = input() word = "" ans = 1 for i in range(len(s)): if i == 0: word = s[i] else: if word >= s[i]: ans += 1 word = s[i] print(ans)
t = set() t.add((1,2)) t.add((5,2)) if (2,1) in t: print(3) else: print(9)
sa = input() sb = input() sc = input() if sa[0] == "a": k = "a" sa = sa[1:] elif sa[0] == "b": k = "b" sa = sa[1:] elif sa[0] == "c": k = "c" sa = sa[1:] while True: if k == "a": if sa != "": k = sa[0] sa = sa[1:] else: print("A") ...
b = input() s = "" for i in range(len(b)): if b[i] == "A": s += "T" elif b[i] == "T": s += "A" elif b[i] == "C": s += "G" else: s += "C" print(s)
import math as m n = int(input()) for i in range(n,-1,-1): if m.sqrt(i) == int(m.sqrt(i)): print(i) exit()
#creates a function that check the month and year to see if there is a friday the 13th. #returns True if friday 13 exists in month and year import sys def f13(m,y): mon = {1:5,2:1,3:1,4:4,5:6,6:2,7:4,8:0,9:3,10:5,11:1,12:3} d = (y + int((y-1)/4)-int((y-1)/100)+int((y-1)/400))%7 if ((y%4 == 0 and y%100 != 0...
lst = [ [2,4,7], [1,7], [5,7], [1,5], [3,4], [7], [1,2,3,6] ] def listmat(lst): return [[1 if j in i else 0 for j in range(1,len(lst)+1)] for i in lst] def matlist(mat): return [[i+1 for i,v in enumerate(j) if v == 1] for j in mat] print('hi') print(matlist(listmat(lst)))
import random class game: def __init__(self): self.table = [0] * 9 self.currentPlayer = 1 self.HAS_WON = 9 self.HAS_LOST = -1 self.HAS_ENDED = -3 self.NO_MOVE = -2 def validMove(self, index): return self.table[index] == 0 def hasWon(self): ...
# Author: Sarah Oertly # Date: 11/19/2019 # Descripton: Write a function named count_letters that takes as a parameter a string and returns a dictionary that # tabulates how many of each letter is in that string. The string can contain characters other than letters, but only # the letters should be counted. The string ...
import copy import random import math import heapq class Puzzle(object): def __init__(self, board): self.board = board self.size = len(board) for i in range(self.size): for j in range(self.size): if self.board[i][j] == 0: self.blank = (i, j)...
from turtle import Turtle ALIGNMENT = "center" FONT = ("Arial", 40, "bold") class Scoreboard(Turtle): def __init__(self) -> None: super().__init__() self.score = [0, 0] self.score_logic() def add_score_left(self) -> None: self.reset() self.score[0] += 1 self.s...
pavala= int(input("")) if (( pavala%400 == 0)or (( pavala%4 == 0) and ( pavala%100 !=0))): print("yes") else: print("no")
import re # If you want to reuse a regex pattern, you can compile it # to create a regex object # Create a postcode pattern pattern = re.compile(r"[A-z]{1,2}[0-9]{1,2}\s?[0-9][A-z]{2}") # Create a postcode pattern thats case-insenstive, using flags pattern = re.compile(r"[a-z]{1,2}[0-9]{1,2}\s?[0-9][a-z]{2}", re.IGN...
'''Dado un vector con personaje de las películas de la saga de Star Wars resolver las siguientes actividades: a. Realizar un barrido recursivo del vector. b. Realizar una función recursiva que permita determinar si ‘Yoda’ está en el vector y en que posición.''' personajes = ['Luke','Han Solo','Obi-Wan','R2-D2','...
def Fibonacci(n): if n<1: return 0 elif n<3: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) n=int(input("Podaj ilość wyrazów ciągu: ")) for i in range(1,n+1): print(Fibonacci(i))
""" The Fibonacci Function This Function is a sequence series of numbers where a number is the addition of the last two numbers, starting with 0, and 1. """ def fibonacci(n): if type(n) != int: return 'Plz Enter a Number' if n<0: return 'Plz Enter a positive Number' if n ==0: retur...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 5 19:14:13 2021 @author: alex """ #Resumen de los datos: dimensiones y estructuras import pandas as pd import os mainpath = "/home/alex/Escritorio/Machine learning/python-ml-course-master/datasets" filename = "titanic/titanic3.csv" fullpath = os...
sample1.txt sample2.txt def swapFileData(): fileName = input("This is a text from: ") file1 = data_a file2 = data_b with open (file1, 'r') as a: data_a = a.read() with open (file1, 'w') as a: a.write(data_b) swapFileData()
# -*- coding: utf-8 -*- """ Created on Sat Sep 28 23:39:32 2019 @author: WEIMIN ZHOU """ N = 100 total = 0 cur = 1.0 for i in range(1, N+1): cur /= i total += cur print(total)
prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15, } for key_list in prices: print key_list print "prices: %s" % prices[key_list] print "stock: %s" % stock[key_list]
# -*- coding: utf-8 -*- """ Created on Sat Sep 28 19:29:01 2019 @author: WEIMIN ZHOU """ from collections import Counter class Solution(object): def uniqueOccurrences(self, arr): """ :type arr: List[int] :rtype: bool """ d = Counter(arr) cnts = d.values() re...
# method 1: maintain a decreasing stack # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def nextLargerNodes(self, head): """ :type head: ListNode :rtype: List[int] ...
# Lucas Williams # Rock Paper Scissors # rps6.py # added comment for github import random # Variables pScore = 0 cScore = 0 ties = 0 cMoves = ["rock", "paper", "scissors"] # Welcome Message (Done) # Print a welcome message print("Welcome to Rock Paper Scissors") # prompt for name pName = input("Wha...
# 时间复杂度:O(n) # 空间复杂度:O(1) class Solution: def climbStairs(self, n: int) -> int: if n <= 2: return n # 初始前面f(0)f(1)f(2) a, b, c = 0, 1, 2 # 迭代出结果 for i in range(n - 2): a, b = b, c c = a + b return c
# 时间复杂度:O() # 空间复杂度:O() from typing import List from Week2 import Node class Solution: # 时间复杂度:O(N) # 空间复杂度:O(N) # 1。迭代 def preorder(self, root: Node) -> List[int]: # 1。基础过滤 if root is None: return [] # 2。初始栈 stack, result = [root], [] # 3。遍历栈 ...
# 함수 def open_account(): print("새로운 계좌가 생성되었습니다.") # open_account() # 전달값과 반환값 def deposit(balance, money): #입금 print("입금이 완료되었습니다. 잔액은 {0}원 입니다.".format(balance + money)) return balance + money def withdraw(balance, money): #출금 if balance >= money: #잔액이 출금보다 많으면 print("출금이 완료되었습...
''' 표준 체중을 구하는 프로그램을 작성하시오 *표준 체중 : 각 개인의 키에 적당한 체중 (성별에 따른 공식) 남자 : 키(m) x 키(m) x 22 여자 : 키(m) x 키(m) x 21 조건1 : 표준 체중은 별도의 함수 내에서 계산 * 함수명 : std_weight * 전달값 : 키(height), 성별(gender) 조건2 : 표준 체중은 소수점 둘째자리까지 표시 (출력 예제) 키 175cm 남자의 표중 체중은 67.38kg 입니다. ''' # my def std_weight(heig...
import string import random characters = list(string.ascii_letters + string.digits + "!@#$%^&*()") def GeneratePassword(): length = int(input("Enter password length: ")) random.shuffle(characters) password = [] for i in range(length): password.append(random.choice(characters)) random.shuffle(password) prin...
#!/usr/bin/env python import numpy as np import sklearn.decomposition def pca_compress(pointcloud, n_components=3): """ Find principal axes of the pointcloud :param pointcloud: The input pointcloud :type pointcloud: numpy.array :return: PCA object fit to the given pointcloud :...
""" Find the element that appears once. We can sum the bits in same position for all the numbers and take modulo with 3. The bits for which sum is not multiple of 3, are the bits of number with single occurrence. """ def find_once(arr): int_size = 32 res = 0 for i in range(int_size): s = 0 ...
""" Given a matrix of '0' or 'X', found the largest subsquare surrounded with 'X'. """ def largest_subsquare(matrix): n = len(matrix[0]) ver = [[0 for col in range(n)] for row in range(n)] hor = [[0 for col in range(n)] for row in range(n)] ver[0][0] = hor[0][0] = int(matrix[0][0] == 'X') # init v...
""" Find the largest multiple of 3. 1.Sort the array in non-decreasing order. 2.Take three queues. One for storing elements which on dividing by 3 gives reminder as 0. The second queue stores digits which on dividing by 3 gives reminder as 1. The third queue stores digits which on dividing by 3 gives reminder as 2. Cal...
""" Given a set of n integers, divide the set in two subsets of n/2 sizes each such that the difference of the sum of two subsets is as minimum as possible. If n is even, then sizes of two subsets must be strictly n/2 and if n is odd, then size of one subset must be (n-1)/2 and size of other subset must be (n+1)/2. """...
""" Print first k digits of 1/n where n is a positive integer. """ def first_k_digit(n, k): res = [] rem = 1 for i in range(k): res.append(int(rem * 10 / n)) rem = (rem * 10) % n return res """ Given a number as string, find the number of contiguous subsequences which recursively add...
""" Longest path in a Directed Acyclic Graph. """ import sys from algorithm.graph.graph import DirectedWeightGraph NINF = -sys.maxsize def longest_path(graph, s): Stack = [] visited = [False] * graph.size() dist = [NINF] * graph.size() dist[s] = 0 for v in range(graph.size()): if not visi...
""" Count number of binary strings without consecutive 1's. """ def count_consecutive(n): prev_prev = 1 prev = 2 cur = 0 for i in range(1, n): cur = prev_prev + prev prev_prev = prev prev = cur return cur def count(n): a = b = 1 for i in range(1, n): a, b ...
""" Efficient program to calculate e^x. The value of Exponential Function e^x can be expressed using following Taylor Series. e^x = 1 + x/1! + x^2/2! + x^3/3! + ... + x^n/n! The series can be re-written as e^x = 1 + x/1 (1 + x/2 (1 + x/3(......))) so we must calculate s(1) s(n-1) = 1 + x/n-1 * s(n) """ def e_power_of...
""" Given a graph and a source vertex src in graph, find shortest paths from src to all vertices in the given graph. Bellman-Ford Algorithm. 1)This step initializes distances from source to all vertices as infinite and distance to source itself as 0. Create an array dist[] of size |v| with all values of infinite except...
# Merge sort for doubly link list class LinkedList: def __init__(self): self.head = None def push(self, v): node = Node(v, None, self.head) if self.head is not None: self.head.prev = node self.head = node def merge_sort(self, temp_head): if temp_head is ...
from heapq import heapify, heappop, heappush # sort a nearly sorted(k sorted) array, # 1.Create a min heap of size k+1 with first k+1 elements # 2.One by one remove min ele from heap, put it in result array, and add a new element to heap from remaining elements def sort_k(arr, k): n = len(arr) # taken first ...
""" Rearrange array such that arr[i] >= arr[j] if i is even and arr[i] <= arr[j] if i is odd and j<i; """ import math def rearrange(arr): arr.sort() idx = math.ceil(len(arr) / 2) odd = arr[:idx] even = arr[idx:] odd_idx = len(odd) - 1 even_idx = 0 for i in range(0, len(arr), 2): ar...
""" Nuts and Bolts Problem. """ def nuts_bolts(nuts, bolts): n = len(nuts) match_pair(nuts, bolts, 0, n-1) def match_pair(nuts, bolts, low, high): if low < high: pivot = partition(nuts, low, high, bolts[high]) partition(bolts, low, high, nuts[pivot]) match_pair(nuts, bolts, low, ...
""" Compare numbers represented by linked list. """ from datastructure.linkedlist.base_linked_list import LinkedList def compare(list1, list2): remove_leading_zero(list1) remove_leading_zero(list2) n1, n2 = list1.size(), list2.size() if n1 != n2: return 1 if n1 > n2 else -1 cur1, cur2 = li...
""" Count number of bits to be flipped to convert A to B. """ def count(a, b): c = 0 a_xor_b = a ^ b while a_xor_b: if a_xor_b & 1: c += 1 a_xor_b >>= 1 return c def smallest_power_of_2(n): if n and not n & n - 1: return n c = 0 while n != 0: c...
""" Swap all odd and even bits. If we take a closer look at the example, we can observe that we basically need to right shift all even bits, and left shift all odd bits by 1. 1)Get all even bits of x by doing bitwise and of x with 0xAAAAAAAA. The number 0xAAAAAAAA is a 32 bit number with all even bits set as 1 and odd ...
# Find k'th smallest elemnt in unsorted array import random import sys def k_smallest(arr, l, r, k): if l <= r: pos = partition(arr, l, r) if pos - l == k - 1: return arr[pos] # go to left subarray if pivot is greater than k if pos - l > k - 1: return k_smal...
def find_unsort_arr(arr): """ 1.Scan left to right find the first element which is greater then next element, let be s 2.Scan right to left find the first element which is smaller than next element, let be e 3.Check whether sorting the candidate unsorted sub array [s, e] makes the complete array sorted ...
""" Compute sum of digits in all numbers from 1 to n. Given a number n, find sum of digits in all numbers from 1 to n. In general, we can compute sum(10^d-1) using below formula sum(10^d -1) = 10*sum(10^(d-1) -1) + 45*10^(d-1) 1)Find the number of digits minus one in n. Let this value be 'd'. For 328, d=2 2)Compute som...
""" Problem: Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. Solution: A simple solution is to place parenthesis at all possible places, calcula...
# Find the closest pair from two sorted arrays import sys def print_closest(a1, a2, x): """ 1) Initialize a variable diff as infinite(Diff is used to store the difference between pair and x), We need to find the minimum diff. 2) Initialize two index variables l and r in the given sorted array. ...
""" Given a positive integer N, count all possible distinct binary string of length N such that there are no consecutive 1's Let a[i] be the number of binary strings of length i which do not contains any two consecutive 1's and which end in 0. Similarly, let b[i] be the number of such strings which end in 1. We can app...
""" Aho-Corasick Algorithm for pattern search. 1.Preprocessing: Build an automation of all words in arr[] the automation has mainly three functions Go to: This function simply follows edges of trie of all words in arr[]. It is represented as a 2D array go[][] where we stored next state for current state and c...
""" Print all permutation of a string. """ def permutation(s, l, res): if l == len(s): print(res) return for cur in range(l, len(s)): s[l], s[cur] = s[cur], s[l] permutation(s, l + 1, res + s[l]) s[l], s[cur] = s[cur], s[l] s = ['A', 'B', 'C'] permutation(s, 0, "") ...
""" Find next greater number with same set of digits. """ import sys def floor_number(arr): n = len(arr) i = j = -1 for k in range(n - 1, 0, -1): if arr[k] > arr[k - 1]: i = k - 1 if i == -1: return None l, h = i + 1, n - 1 while l < h: m = ((l + h) >> 1) + ...
def binary_search_recur(arr, x, l, r): if l > r: return -1 mid = l + ((r - l) >> 1) # 取中位数 防止int溢出 if arr[mid] > x: # mid不用取,忘前挪一位 return binary_search_recur(arr, x, l, mid - 1) elif arr[mid] < x: # mid忘后挪一位 return binary_search_recur(arr, x, mid + 1, r) else...
""" Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. Let f(i, s) be the if the arr[0..i] have a subset with sum equal to s, then it can write in following formula f(i, s) = f(i-1, s) or f(i-1, s-a[i]) """ def equal_2_sum(arr, i, s): ...
""" DFA based division. """ def DFA_division(n, k): FA = build_DFA(k) return division_util(FA, n) def build_DFA(k): FA = [] for state in range(k): item = [0]*2 trans0 = state * 2 item[0] = trans0 if trans0 < k else trans0 - k trans1 = state * 2 + 1 item[1] =...
""" Collect maximum points in a grid using two traversals. Given a matrix where every cell represents points. How to collect maximum points using two traversals under following conditions. Let the dimensions of given grid be R*C: 1)The first traversal starts from top left corner, i.e.,(0,0) and should reach left bottom...
""" Multiply a given number with 3.5. """ def multiply_with_3_point_5(n): return (n << 2) - (n >> 1) def turn_off_rightmost(n): return n & (n - 1) n = -4 print(multiply_with_3_point_5(n), n * 3.5) print(turn_off_rightmost(12))
import random class TriParTas: def __init__(self, list_length): self.list_to_tri = [] self.list_tri = [] self.list_length = list_length self.born_inf = 0 self.born_sup = 1000 def generate_list(self): self.list_to_tri = [random.randint(self.born_inf,...
class Result: def __init__(self): self.salary_before_tax = 0 self.salary_after_tax = 0 self.tax_20_pay = 0 self.tax_40_pay = 0 self.tax_45_pay = 0 self.ni_12_pay = 0 self.ni_2_pay = 0 self.pension_percent = 0 self.pension = 0 def get_a...
# -*-coding:Latin-1 -* import os annee = int(input("Saisissez une annee : ")) if annee % 400 == 0 or (annee % 4 == 0 and annee % 100 != 0): print("L'annee saisie est bissextile.") else: print("L'annee saisie n'est pas bissextile.") os.system("pause")
class Sudoku: # method used to check validity of the inputs in sudoku def solution(self): T = int(input()) for i in range(T): mat = [x for x in input().replace("0",".").split()] array = [] for i in range(0,81,9): array.append(mat[i:i+9]...
# creating the Node class to frame a single node class Node: def __init__(self,data): self.data = data self.next = None # creating a Linked List class to get all the helper functionalities inside class LinkedList: def __init__(self): self.head = None self.tail = None def ap...
def union (a,b,m,n): #add both the array result = a+b #return the sorted array # set() does not contain any duplicate elements return sorted(set(result)) #Driver's code a=[2,2,3,4,5] b=[1,1,2,3,4] m= len(a) n= len(b) print(union(a,b,m,n))
import sqlite3 from tkinter import * from tkinter.ttk import * def disp_meaning(i): e1.delete(0, END) global word word = list.get(ACTIVE) cur = conn.execute('select * from words') for j in cur: if j[1] == word: e1.insert(0, j[2]) e1.focus() def edit(): conn.execute('update words set meani...
assignments = [] def assign_value(values, box, value): """ Please use this function to update your values dictionary! Assigns a value to a given box. If it updates the board record it. """ # Don't waste memory appending actions that don't actually change any values if values[box] == value: ...
### YOUR CODE FOR chocolatePrice() FUNCTION GOES HERE ### def hcf(ali_budget,bashir_budget): if ali_budget > bashir_budget: smaller = bashir_budget else: smaller = ali_budget for i in range(1, smaller+1): if((ali_budget % i == 0) and (bashir_budget % i == 0)): hcf = i ...
import math def is_increasing(n): for i in range(0, len(n)-1): if int(n[i]) > int(n[i+1]): return False return True def is_decreasing(n): for i in range(0, len(n)-1): if int(n[i]) < int(n[i+1]): return False return True def is_bouncy(n): return not is_dec...
#!/usr/bin/env python # -*- coding: utf-8 -*- # JESSE RUBIN - Biblioteca from functools import reduce from operator import mul from collections import Counter, deque def chunks(list, chunk_size): """Yields chunks of a list with length == chunk_size Args: list (list or tuple): list to be broken up ...
velocidade = int(input('Digite sua velocidade: ')) if velocidade > 110: multa = (velocidade - 110) * 5 print('Sua multa R$ %d.' %multa) if velocidade <= 110: print('Voc no foi multado. Parabns!')
#Program to check if entered number is even or not x = int(input("Enter a number to check!")) if x%2==0: print("Entered Number was even") else: print("The Number is odd")
"""scalar product""" from typing import List def scalar_product(list_a: List[int], list_b: List[int]): """return dot""" lgth_a = len(list_a) lgth_b = len(list_b) if lgth_a == 0 or lgth_b == 0: return 0 dot = 0 if lgth_a == lgth_b: for i in range(lgth_a): prod = l...
import pygame from random import randint from board import * import sys r = 0 g = 0 b = 0 clock = pygame.time.Clock() fps = 50 def terminate(): sys.exit() class Button: def __init__(self, x, y, h, w, text): self.x = x self.y = y self.h = h self.w = w self.text = text...
''' Visualize some basic statistics of our dataset. ''' import numpy as np from matplotlib import pyplot as plt def compute_stats(array): stats = [] data = [] data.append(array[0][201]) # Letter a data.append(array[1][126]) # Letter b data.append(array[2][47]) # Letter c for i in...