text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- # @Time : 2020/4/22 12:09 # @Author : WuxieYaYa """ 给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。 示例: 输入: [1,2,3,null,5,null,4] 输出: [1, 3, 4] 解释: 1 <--- / \ 2 3 <--- \ \ 5 4 <--- 链接:https://leetcode-cn.com/problems/binary-tree-right-side-view...
# -*- coding: utf-8 -*- # @Time : 2020/6/19 22:50 # @Author : WuxieYaYa """ 给定一个二叉树,检查它是否是镜像对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1 / \ 2 2 \ \ 3 3 链接:https://leetcode-cn.com/problems/symmetric-tree """ from full_...
# -*- coding: utf-8 -*- # @Time : 2020/11/5 14:49 # @Author : WuxieYaYa from typing import List def binary(rootVal): return [rootVal, [], []] def insertLeft(root: List, newBranch): t = root.pop(1) if len(t) > 1: root.insert(1, [newBranch, t, []]) else: root.insert(1, [newBranch,...
# -*- coding: utf-8 -*- # @Time : 2020/6/13 23:35 # @Author : WuxieYaYa """ 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 示例: 输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] 链接:https://leetcode-cn.com/problems/combinations """ def combine(n, k): l = [i + 1 for i in range(n)] an...
import math import os import sys from datetime import timedelta import requests print('hello') # Python program for implementation of MergeSort def mergeSort(arr): if len(arr) >1: mid = len(arr)//2 #Finding the mid of the array L = arr[:mid] # Dividing the array elements R = arr[mid...
import sys def clear(): # TODO Complete with your code and remove print below. print 'clear' # Inserts a job offer into the database. def insert(fieldValues): # TODO Complete with your code and remove print below. print 'insert ' + str(fieldValues) # Updates all job offers that attend the field_name=ol...
# Functions for students to implement. def solveOnlyLists(inputList): uniqueList = [] #compute unique items in inputList for x in inputList: if x not in uniqueList: uniqueList.append(x) return uniqueList def solveDict(inputList): #compute unique items in inputList uniqueDict...
# Functions for students to implement. # Performs search in unsorted L. # L might not be sorted. Can't use sorting to solve this. def searchGreaterNotSorted(L, v): return -1 # Performs search in sorted L (ascending order). # L is sorted. def searchGreaterSorted(L, v): return -1 # Performs binary search in sort...
import math # Functions for students to implement. # Performs search in unsorted L. # L might not be sorted. Can't use sorting to solve this. def searchGreaterNotSorted(L, v): return sum([1 for x in L if x > v]) #return -1 # Performs search in sorted L (ascending order). # L is sorted. def searchGreaterSorted(...
from typing import List def quick_sort(arr: List[int]) -> List[int]: """Sorts an array by using quick sort algorithm. It chooses pivot from the array and compares elements against it, splitting it into two arrays(smaller and larger). Then, recursively sorts the arrays. """ if len(arr) < 2:...
""" 1: centroids are randomly selected from dataSet in initCentroids() 2: point is selected from dataSet and assigned to cluster in assignNewPointToCluster() a: euclideanDistance() is called to assign to closest existing cluster 3: centroid of the cluster the point was assigned to is recalculated in recalculateCe...
import pandas as pd import numpy as np from random import shuffle def get_data(): file_path = 'dataset\iris.data' #Define attribute names for dataframe column attributes = ['slength', 'swidth', 'plength', 'pwidth' , 'class', 'label'] data = pd.read_csv(file_path, names= attributes) ...
c = 'a' print(c) s = "Bonjour" print(s) nom = "Boreal" # Concatenation print(s + " " + nom) # longueur de la chaine de charactere - fonction longueur = len(nom) print(longueur) c =' bonsoir' print (c) canada = "Toronto" I ="300117791" print (canada+" "+I) longeur = name(Misé) print(longeur)
def main() x = 0 while(x<5): print(x) x = x+1
def insertion_sort(array): index_length = range(1, len(array)) for i in index_length: value_to_sort = array[i] # store the value to sort as a variable. while array[i-1] > value_to_sort and i > 0: # while loop to compare the value to the value on its left. array[i], array[i-1] = array[i-1], array[i] ...
import sys import os from queue import PriorityQueue class MyPriorityQueue(PriorityQueue): def peek_top_priority(self): return self.queue[0] # --------------------------------------------------------------- class MyReversePriorityQueue(PriorityQueue): def put(self, num): num *= -1 Prior...
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ all = 0 original = x if x < 0 : return False else: while x != 0: Digits = x % 10 all = (all + Digits)*10 ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode "...
def add(*args): return sum(args) # ALTERNATIVE SOLUTION # total = 0 # for arg in args: # total += arg # return total def multiply(*args): total = 1 for arg in args: total *= arg return total def maximum(*args): return max(args) # ALTERNATIVE SOLUTIO...
#sql.py import sqlite3 def stringifyCol(columns): toString = "" for tuple in columns: toString += tuple[0] + " " + tuple[1] + ", " return toString[:-2] def stringifyVal(values): toString = "" for value in values: toString += "'" + value + "'," return toString[:-1] class databaseObj: def __init__(self): ...
# -*- coding: utf-8 -*- # Groupe 4 # DELOEUVRE Noémie # Céline MOTHES # Morgan SEGUELA import os import json import datetime as date import csv import re def add_to_index(date, text, newspaper): hash_text = get_hash(date, text, newspaper) with open("hash_text.csv", "a") as f: f.write(hash_text + ",") ...
import re class State: def __init__(self, x, y, direction): self.x = x self.y = y self.direction = direction turn_map = {'L': {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}, 'R': {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}} forward_map = {'N': 1, 'E': 1, 'S': -1, 'W': -1} format_directions = l...
from . import formatter, message def On2(data : list, totalHeight: int, fromDict=True): """This algorithm represents the O (n ^ 2) optimization and it does not need to do what it should do, it only represents the upper limit of the test on python Args: data (list): List of data that will be c...
# first = "shubham" # last = "latkar" # # print(f'{first} [{last}] is coder') # msg = "My name is Shubham Latkar" # print(msg.replace("Shubham ", "Shubham Kiran ")) # print("Shubham" in msg) # print(len(msg)) # print(msg.title()) print(10/3) print(10//3) print(10 % 3) print(10 ** 3)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 13 10:49:22 2016 @author: RashidKazmi """ # We defined: stooges = ['Moe','Larry','Curly'] # but in some Stooges films, Curly was # replaced by Shemp. # Write one line of code that changes # the value of stooges to be: ['Moe','Larry','Shemp'] #...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 13 12:07:51 2016 @author: RashidKazmi """ # Define a procedure, find_element, # that takes as its inputs a list # and a value of any type, and # returns the index of the first # element in the input list that # matches the value. # If there is no ...
# Write Python code that prints out the number of hours in 7 weeks. hrs_one_day = 24 days_in_week = 7 hours_in_week = (hrs_one_day * days_in_week*7) print (hours_in_week) print (24*7*7)
# Define a procedure, bigger, that takes in # two numbers as inputs, and returns the # greater of the two inputs. def bigger (x, y): if x > y : return x else: return y print (bigger (3,5)) #>>> 7 print (bigger (3,2)) #>>> 3 print (bigger (3,3)) #>>> 3
from random import randint # Constants X_0 = ["X", "0"] # Playing characters NUM_OF_PLAYERS = 2 # Number of players BOARD_SIZE_RANGE = range(2, 11) ##### Board ############## ##### Init Board ######### def init_board(board_size): if board_size not in BOARD_SIZE_RANGE: print("Error: wrong entered board ...
#02장 파이썬 프로그래밍의 기초, 자료형 ####### Practice02-1 (숫자형) # - 8진수 만들때는 숫자가 0O or 0o로 시작 ex) a = 0o177 # - 16진수 만들때는 숫자가 0x로 시작 ex) a = 0x8ff a = 3 b = 4 print(a + b) print(a ** b) #a의 b제곱 ####### Practice02-2 (문자형 자료형) # - 문자열 만들때 "Hello World", 'Hello World', """Hello World""", '''Hello World''' food = "Python's favorite...
#!/usr/bin/env python3 import re def validate_user(username, minlen): """Checks if the received username matches the required conditions.""" if type(username) != str: raise TypeError("username must be a string") if minlen < 1: raise ValueError("minlen must be at least 1") # Usernames...
print "I will now count my chickens:" # prints out count of chicken. print "Hens", 25.0 + 30.0 / 6.0 # print no. of hens print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 # print no. of rooster print "Now I will count the eggs:" #print out "now I will count eggs" print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 # ...
#!/usr/bin/env python import sys import re # parse one row from file input def pb_parse_input_row(row): name = re.sub('\d', '', row) # remove digits name = name.replace('\n', '') number = re.sub('\D', '', row) # remove non-digits return name.strip(), number # parse output string from name & number...
from user_interface import * from sweepstake import Sweepstake from contestant import Contestant """Using dependency injection to make adding and removing sweepstakes""" class MarketingFirm: def __init__(self, manager): self.manager = manager def create_sweepstakes(self): sweepstakes_name = ge...
""" Author: Abdullah Najjar Version: 0.1 Description: This game is called Adventure # TODO: Fix player speed and problem in movement, also screen size issues + add map tiling """ import arcade import os import random # Global variables SPRITE_SCALING = 0.5 #Character size SPRITE_SCALING_COIN = .50 #Size of coins COIN_...
''' friends = ['ram','aam','sam','jam'] partyer = ['tity','namu','ram','sam'] party_p = { names for names in set(friends).intersection(set(partyer)) } print(party_p) ''' friends = {'ram','aam','sam','jam'} partyer = {'tity','namu','ram','sam'} party_p = { names for names in (friends).intersection((partyer)) ...
def test_array_functions(): arr = [3, 4, 67, 23, 5, 7, 8, 9] print(arr) print("Index of 7 in array: ", arr.index(7)) arr.pop() ## pop the last element in array print(arr) print("Sorted array: ", sorted(arr)) arr.append(45) ## Appends element at the end of array print(arr) arr.reverse...
#!/usr/bin/python class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount +=1 def displayCount(self): print("Total Employee: %d" % Employee.empCount) def displayEmp...
import random highest = 10 answer = random.randint(1,highest) guess = 0 print("Please guess a number between 1 & 10") while guess != answer: guess=int(input()) if guess == 0: break if guess < answer: print("Please select higher no") elif guess > answer: print("Please select lower no") else: print("Wel...
def partition(A,start,end): pivot=A[end] pindex=start for i in range(start,end): if A[i]<=pivot: A[i],A[pindex]=A[pindex],A[i] pindex+=1 A[pindex],A[end]=A[end],A[pindex] return(pindex) def qsort(A,start,end): if start<end: pindex=partition(A,start,end) qsort(A,start,pindex-1) qsort(A,pind...
int_num = 10 float_num = 20.0 print(int_num) print(float_num) a = 10 b = 20 print("*******************") add = a + b print(add) sub = b - a print(sub) multi = a * b print(multi) div_mychoice = b / a print(div_mychoice)
# This is a one line comment # Exponentiation # 10 * 10 ... 20 exponents = 10 ** 20 print(exponents) """ This is a multi-line comment Modulo - It returns the remainder """ remainder = 11 % 3 print(remainder)
""" Data type to store more than one value in one variable name List items are in brackets, separated with "," [ 1, 2, 3 ] """ cars = [ "bmw", "honda", "audi"] empty_list = [] print(empty_list) print(cars) print("*#"*20) print(cars[1]) num_list = [1, 2, 3] sum_num = num_list[0] + num_list[1] print...
#!/usr/bin/python # coding=utf-8 import os def rename_files(): file_list = os.listdir(r"C:\prank") saved_path = os.getcwd() print "Current path is " + saved_path os.chdir(r"C:\prank") for filename in file_list: print "Old name " + filename print "New name " + filename.translate(Non...
import torch.nn as nn import torch.nn.functional as F import torch # Declare convolution layers: class SimpleCNN_net(nn.Module): def __init__(self): super(SimpleCNN_net, self).__init__() # loss_history is a list contain prediction error of the model through the training dataset # acc_hist...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import random import verbose import deserializer from sentence import Sentence class NoWordFound(Exception): """No word was found.""" pass class SentenceGenerator(object): """Sentence generator.""" def __init__(self, chains): """Constructs ...
#Indi Knighton #14/10/2014 #Program which will say "Hello World" 10 times for counter in range(1,11): print("Hello World")
def cubed(x,y=3): value = x**y return value mf = open('input.txt') mf_read = mf.read().splitlines() print(str(mf_read)) mf_int = [int(i) for i in mf_read] print(mf_int) mf_cube = [] for i in mf_int: mf_cube.append(cubed(i)) mf_str = [str(i) for i in mf_cube] print(mf_cube) with open ('cubed.txt', mode = 'wt...
""" Given an array of 4 digits, return the largest 24 hour time that can be made. The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight. Return the answer as a string of length 5. If no valid time can be made, return an empty stri...
""" Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... Example 1: Input: 1 Output: "A" Example 2: Input: 28 Output: "AB" Example 3: Input: 701 Output: "ZY" """ class Soluti...
""" Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer. Example 1: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Constraints: 1 <= arr.length <= 10^4 0 <= arr[i] <= 10^5 """ def find_special_integer(nums): ...
def word_split(phrase, list_of_words, output=None): if output is None: output = [] for word in list_of_words: if phrase.startswith(word): output.append(word) return word_split(phrase[len(word):], list_of_words, output) return output # print(word_split('themanran'...
""" Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left ...
class Node(object): def __init__(self, value): self.value = value self.nextnode = None def cycle_check(node): marker1 = node marker2 = node while marker2 != None and marker2.nextnode != None: marker1 = marker1.nextnode marker2 = marker2.nextnode.nextnode if marke...
""" Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Example: ...
""" You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Example 2: Input: coordinates = [[1,1],[2,2],[3,4]...
""" In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. Return the element repeated N times. Example 1: Input: [1,2,3,3] Output: 3 Example 2: Input: [2,1,2,5,3,2] Output: 2 Example 3: Input: [5,1,5,2,5,3,5,4] Output: 5 Note: 4 <= A.length <= 10000 0 <...
""" Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. Example 1: Input: nums = [1,1,2] Output: [[1,1,2], [1,2,1], [2,1,1]] Example 2: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Constraints: 1 <= nums.l...
""" Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 Clarification: What should we return when needle is an empty...
""" Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.rig...
''' for problem definition, check out the following url: https://app.codility.com/programmers/task/number_of_disc_intersections/ ''' class DiscLog(): def __init__(self, x, start_end): self.x = x self.start_end = start_end def disc_intersections_1(arr): disc_history = [] for i in range(l...
""" On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points. You can move according to the next rules: In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertic...
""" Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Note: You may assume the string contains only lowercase alphabets. Follow up: What if the inputs contain unicode cha...
""" n a list of songs, the i-th song has a duration of time[i] seconds. Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0. Example 1: Input: [30,20,150,100,40] Output: 3 E...
class BinaryTree(object): def __init__(self, root_obj): self.key = root_obj self.left = None self.right = None def insert_left(self, new_node): if self.left is None: self.left = BinaryTree(new_node) else: t = BinaryTree(new_node) t.lef...
# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... # # The next number is found by adding up the two numbers before it. # # The 2 is found by adding the two numbers before it (1+1) # The 3 is found by adding the two numbers before it (1+2), # And the 5 is (2+3), # and so on! # we use memoization technique to accelerate computing....
""" Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. Examples: Input: S = "a1b2" Output: ["a1b2", "a1B2", "A1b2", "A1B2"] Input: S = "3z4" Output: ["3z4", "3Z4"] Input: S = "12345" Output: ["123...
""" Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.) Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5. Example 1: Input: [0,1,1] Output: [true,false,false...
""" A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum. Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous). Example 1: Input: [[4,3,8,4], [9,5,1,9], ...
""" Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent ...
""" Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # ...
""" X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each oth...
""" Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can. Example 1: Input...
""" Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows: Characters ('a' to 'i') are represented by ('1' to '9') respectively. Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. Return the string formed after mapping. It's guarante...
''' Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. If possible, output any possible result. If not possible, return the empty string. Example 1: Input: S = "aab" Output: "aba" Example 2: Input: S = "aaab" Output: "" Note: S will co...
def pascal_triangle(n): if n < 0: return [] res = [[1], [1, 1]] if n <= 2: return res[:n] pre_line = res[1] for i in range(n-2): current_line = pre_line.copy() current_line.append(1) for j in range(1, i+2): current_line[j] = pre_line[j-1] + ...
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ def main(): x = [5] kitten(x) print(f'in main : x is {x}') # Cualquier argumento con default debe estar detrás que el resto. def kitten(a): a[0] = 3 print('Meow.') print(a) # Indica que que aquí se encuentra el principal if __...
x = 42 # Usando py versión 3 se usa format para dar formato. Versiones anteriores se hacía con placeholdars. era %d y luego # pasando el valor que ese placeholder admitiera print('Hello World. %d' % x) # forma normal de hacerlo print('Hello World. {}'.format(x)) # forma más actual de hacerlo print(f'Hello World. {x}')
# with no header def calulate_BMI(height,weight): BMI = weight/(height*height) return BMI import csv lineCount = 0 with open('a.csv') as csvFile: csvReader = csv.reader(csvFile, delimiter=',') for row in csvReader: if lineCount == 0: print(f'Column names are: {", ".join(row)}')...
# Represents a blackjack game # Classes to represent the cards themselves class Card(object): """ A Playing card """ RANKS = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] SUITS = ['C','D','H','S'] def __init__(self, rank, suit): self.rank = rank self.suit = suit def __str__(self): return self....
hrs = input("Enter Hours:") try: h = float(hrs) except: h = - 1 if h > 0 : print ('Nice work') else: print ('Not a number') quit() rate = input("Enter pay rate:") try: r = float(rate) except: r = - 1 if r > 0 : print ('Nice work') if h <= 40: p...
#################### IMPORTS ####################### from tkinter import * from tkinter import ttk import random ################## CLASS CODE ###################### # Create the Account class class Account: """The Account class stores the details of each account and has methods to deposit, withdraw an...
import MapReduce import sys """ Word Count Example in the Simple Python MapReduce Framework """ TABLE1 = 'order' TABLE2 = 'line_item' mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: document identifier # value: document contents table...
#!/usr/bin/env python # coding: utf-8 # # Python Machine Learning - AI implementation in Credit Card Scam Detection # #### *It detects and labels the output as fraud and not fraud according to the test dataset. Since it's a binary classification logistic regression provided better results than that of the other classi...
from tkinter import * from tkinter import Text root=Tk() canvas=Canvas(root,width=700,height=300) canvas.pack() lab1=Label(root,text="Practical Assignment-0",fg="black",font=('Arial',18)) lab1.place(relx=0.25,rely=0,relheight=0.2,relwidth=0.5) l1=Label(root,text="Plaintext",fg="black",font=('Verdana',11)...
base = int(input("Ingrese la base del triangulo: ")) altura = int(input("Ingrese la altura del triangulo: ")) area = (base*altura)/2 print("El área del triangulo es: ", area)
calificaciones = {'matematicas':5,'ingles':4.5,'espanol':3,'estadistica':1} mayor=0 for clave,valor in calificaciones.items(): #print("%s -> %s " %(clave,valor)) if valor >= mayor: mayor=valor materia_mayor=clave print("La materia con mejor promedio es: %s " %(materia_mayor))
lista_numeros=[] numero_del_usuario="" while len(lista_numeros) < 10: while not numero_del_usuario.isdigit(): numero_del_usuario= input("Introduce un numero: ") lista_numeros.append(numero_del_usuario) numero_del_usuario="" print("Número añadido") numero_grande = lista_numeros[0] for numero ...
string_inicial=input("Introduce una string: ") str_final=string_inicial.replace("a","VACA").replace("A","VACA") print(str_final)
helado_input=(input("¿Quieres un helado? (si/no) ")).upper() if helado_input == "SI": helado= True elif helado_input=="NO": helado= False else: print("si o no monger") helado= False dinero_input=(input("¿Tienes dinero para un helado? (si/no) ")).upper() esta_tu_tia_input= input("¿esta tu tia? (si/no) ...
lista_numeros =[] numeros_usuario =input("Introduce un numero: ") print("Número añadido correctamente") while numeros_usuario != "fin": lista_numeros.append(numeros_usuario) numeros_usuario =input("Introduce un numero: (Escribe <fin> para terminar)") print("Número añadido correctamente") suma =0 for i in...
''' @author: vivek ''' from PIL import Image class PyImage(object): ''' classdocs ''' def __init__(self, filename): ''' Constructor ''' self.image = Image.open(filename) self.pixels = self.image.load() def get_rgba(self, pixelx, pixely): ''' ...
'''Convert png to txt using pytesseract module, a python wrapper for Google's Tesseract-OCR library References: - [Pytesseract](https://github.com/madmaze/pytesseract) - [Tesseract for Windows](https://github.com/UB-Mannheim/tesseract/wiki) - [Tesseract HOWTO](https://www.learnopencv.com/deep-learning-based-text-recogn...
# Introdução a Programação de Computadores - IPC # Universidade do Estado do Amazonas - UEA # #Ulisses Antonio Da Costa 1515090555 #Thiago ferreira Aranha 1715310047 #vitor simões Azevedo 1715310025 #victor hugo de oliveira carreira 1715310063 #Reinaldo vargas 1715310054 #-----------...
x = [2,3,6,7,89,7,56,4,3,346,67,8] #x.append(2) # append 2 at the end #x.insert(2,999) # append 999 at index 2 #x.remove(2) #removes the first 2 #x.remove(x[2]) # removes the 3rd element of the list #print(x) #print(x[5:7]) # slices the data from index 5 to index 7 => result = 56,4 #print(x[-1]) # prints the last e...
def getBy(list,even=True): newList = [] for i in range(len(list)): if even and i%2 == 0: newList.append(list[i]) elif not even and i%2 != 0: newList.append(list[i]) return newList number = int(input().strip()) for i in range(number): list = input().strip() pr...
# heights = [1, 1, 4, 2, 1, 3] heights = [1, 2, 3, 4, 5] heights_sorted = sorted(heights) c = 0 for i in range(len(heights)): if heights[i] != heights_sorted[i]: c += 1 print(c)
nums = [-4,-1,0,3,10] for i in range(len(nums)): nums[i] = pow(nums[i], 2) nums.sort() print(nums) # compare operations def square(n): return n*n result = list(map(square, nums)) result.sort() print(result)
# import heapq # class Solution: # def findKthLargest(self, nums: List[int], k: int) -> int: # # nums.sort() # # self.insertionSort(nums) # # nums = self.heapSort(nums) # nums = self.mergeSort(nums) # return(nums[len(nums)-k]) # def insertionSort(self, nums): # fo...
class Vector(): def __init__(self, d): self._coords = [0]*d def __len__(self): return len(self._coords) def __getitem__(self, j): return self._coords[j] def __setitem__(self, j, val): self._coords[j] = val def __sub__(self, other): if len(self) != len(...