text
stringlengths
37
1.41M
# 有效的字母异位词 # 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。 # 说明: # 你可以假设字符串只包含小写字母。 class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ # ranking 54%:转换成列表,然后排序,比较两个排序后的列表是否相同 if len(s) != len(t): return False ...
# 位1的个数 # 编写一个函数,输入是一个无符号整数, # 返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ # 参考:http://www.cnblogs.com/klchang/p/8017627.html MAX_INT = 4294967295 # 按位与运算 # 对整数的二进制表示的每一位与 1 求...
# 颠倒整数 # 给定一个 32 位有符号整数,将整数中的数字进行反转。 # 注意:假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。 # 根据这个假设,如果反转后的整数溢出,则返回 0。 class Solution: def reverse(self, x): """ :type x: int :rtype: int """ if x == 0 or x>2**31: return 0 else: l = list(str(x)) ...
# 字谜分组 # 给定一个字符串数组,将字母异位词组合在一起。 # 字母异位词指字母相同,但排列不同的字符串。 class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ # 字典,key为每一个单词排序后的字符串 # https://juejin.im/pin/5ad07aa5092dcb5883283ffc bucket = {} for ele in ...
# 爬楼梯 # 假设你正在爬楼梯。需要 n 步你才能到达楼顶。 # 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? # 注意:给定 n 是一个正整数。 class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ # https://blog.csdn.net/guoziqing506/article/details/51646800 # 走到第i级台阶的走法:f[i] = f[i - 1] + f[i - 2] ...
# -*- coding: utf-8 -*- """ Created on Tue Sep 22 17:25:44 2020 @author: aksha """ import mysql.connector mydb = mysql.connector.connect( host="localhost", user="akshay", password="Cstar_2033", database="naticus" ) cursor = mydb.cursor() #DISPLAYS RESULT DIRECTLY cursor.execute("CREATE D...
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 import sys import argparse import os """ Learning Argparse """ #TODO - Use this function to validate the input def dir_arg(arg): if os.path.isdir(arg): return arg ...
""" The goal of Artificial Intelligence is to create a rational agent (Artificial Intelligence 1.1.4). An agent gets input from the environment through sensors and acts on the environment with actuators. In this challenge, you will program a simple bot to perform the correct actions based on environmental input. Mee...
""" You need to construct a feature in a Digital Camera, which will auto-detect and suggest to the photographer whether the picture should be clicked in day or night mode, depending on whether the picture is being clicked in the daytime or at night. You only need to implement this feature for cases which are directly d...
# -*- coding: utf-8 -*- """ Created on Sat Nov 23 11:28:44 2019 @author: JUFRI """ import re def arkademy(k): a=re.findall("[a-zA-Z]", k) if a: print("Ini Bukan Angka!") else: x=int(k) print (x) i=1 while i<=x: if i%3!=0 and i%7!=0: ...
# -*- encoding: utf-8 -*- """A module for seeing if you have the right amount of parantheses.""" def proper_parens(string): """Test if the number of "(" matches the number of ")".""" status = 0 for char in string.strip(): if char == "(": status += 1 elif char == ")": ...
""" 两个字符串是变位词 描述 笔记 数据 评测 写出一个函数 anagram(s, t) 判断两个字符串是否可以通过改变字母的顺序变成一样的字符串。 您在真实的面试中是否遇到过这个题? 样例 给出 s = "abcd",t="dcab",返回 true. 给出 s = "ab", t = "ab", 返回 true. 给出 s = "ab", t = "ac", 返回 false. """ class Solution: """ @param s: The first string @param b: The second string @return tr...
""" 最大数 给出一组非负整数,重新排列他们的顺序把他们组成一个最大的整数。 最后的结果可能很大,所以我们返回一个字符串来代替这个整数。 样例 给出 [1, 20, 23, 4, 8],返回组合最大的整数应为8423201。""" ###https://docs.python.org/2/howto/sorting.html#sortinghowto class Solution: #@param num: A list of non negative integers #@return: A string def largestNumber(self, num): length ...
""" 给你一个包含 m x n 个元素的矩阵 (m 行, n 列), 求该矩阵的之字型遍历。 您在真实的面试中是否遇到过这个题? 样例 对于如下矩阵: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10, 11, 12] ] 返回 [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12] """ class Solution: # @param: a matrix of integers # @return: a list of integers def printZMatrix(self, matrix): row =...
""" 跳跃游戏 II 给出一个非负整数数组,你最初定位在数组的第一个位置。 数组中的每个元素代表你在那个位置可以跳跃的最大长度。    你的目标是使用最少的跳跃次数到达数组的最后一个位置。 样例 给出数组A = [2,3,1,1,4],最少到达数组最后一个位置的跳跃次数是2(从数组下标0跳一步到数组下标1,然后跳3步到数组的最后一个位置,一共跳跃2次)""" #://leetcode.com/discuss/422/is-there-better-solution-for-jump-game-ii?show=422#q422 """ In DP, if you use an array to track the min step ...
""" 给定一个文档(Unix-style)的完全路径,请进行路径简化。 您在真实的面试中是否遇到过这个题? Yes 样例 "/home/", => "/home" "/a/./b/../../c/", => "/c" 挑战 你是否考虑了 路径 = "/../" 的情况? 在这种情况下,你需返回"/"。 此外,路径中也可能包含双斜杠'/',如 "/home//foo/"。 在这种情况下,可忽略多余的斜杠,返回 "/home/foo"。""" class Solution: # @param {string} path the original path # @return {string} the si...
def mergeSort(aList): if len(aList)<= 1: return aList mid= len(aList)/ 2 left= mergeSort(aList[:mid]) right= mergeSort(aList[mid:]) return merge(left,right) def merge(left,right): result= [] i,j= 0,0 while i< len(left) and j< len(right): if left[i]<= right[j]: resul...
""" 对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。 说明 在面试中我是否需要实现KMP算法? 不需要,当这种问题出现在面试中时,面试官很可能只是想要测试一下你的基础应用能力。当然你需要先跟面试官确认清楚要怎么实现这个题。 样例 如果 source = "source" 和 target = "target",返回 -1。 如果 source = "abcdabcdefg" 和 target = "bcd",返回 1。""" class Solution: def strStr(sel...
texto = 'Hello world' # Nos muestra todo lo que podemos hacer con este tipo de datos. # dir(texto) print(dir(texto)) print(texto.upper()) print(texto.lower()) print(texto.swapcase()) print(texto.capitalize()) print(texto.replace('Hello', 'bye')) print(texto.count('l')) # output 3 porque la "l" sale 3 veces en el text...
x=int(input("1st value")) y=int(input("2nd value")) z=int(input("3rd value")) print(max(x,y,z)) print(min(x,y,z))
for i in range(1,50): if i<=7: print("square of the no.",i*i)
from sys import argv # Python program opening files script, filename = argv with open(filename) as txt: print(f"Here's your file {filename}") print(txt.read()) print("Type the filename again") file_again = input(">") with open(filename) as txt_again: print(txt_again.read())
# This code is contributed by PranchalK """Another AVL tree implementation with inversion count incorporated.""" # An AVL Tree based Python program to # count inversion in an array from typing import Any, List, Optional class Node: """New Node.""" # Allocates a new # Node with the given key and NULL ...
# Licensed under MIT License. # See LICENSE in the project root for license information. """Timsort implementation.""" # This algorithm finds subsequences that are already ordered (called "runs") and uses # them to sort the remainder more efficiently. It is a hybrid of insertion sort and # merge sort, taking advant...
# Licensed under MIT License. # See LICENSE in the project root for license information. """Linked list implementation.""" from typing import Any class Node: """Node in a linked list.""" def __init__(self, data: Any) -> None: self.data = data self.next = None class LinkedList: """L...
import random def MAGIC_NUMBER_CONSOLE_TITLE(): print("\n====MAGIC NUMBERS====") print("---------------------") print("= Try to guess the ==") print("= magic number in ==") print("= {} chances or less = ".format(chances)) print("=====================") # generates a list of random, positi...
def foo (): width = int (input ("Введите ширину: ")) height = int (input ("Введите высоту: ")) s = input ("Из чего состоит рамка: ") if (width < height): #Если ширина меньше высоты j=1 i=0 for i in range(0, width-1): print(s, end='') while (i < height): ...
"""Simple model building blocks.""" import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class PositionAwareAttention(nn.Module): """ A position-augmented attention layer where the attention (adapted from https://github.com/yuhaozhang/tacred-r...
""" Module provides datastructures for tabular data, and function for reading csv files. """ from collections import defaultdict import csv import numbers class DataTable: """ Two-dimensional, potentially heterogeneous tabular data. Can be thought of as a dict-like container for List objects, where the key ...
a, b = 23, 21 c = 2**8-1 # To show what happens when you select a bad set of values, # set c = 2**8 and watch what happens to 'x % 2' # It will always flip between 0 and 1 -- i.e. is 100% predictable def lcg_generate(x): return (a * x + b) % c # This generates a full set of cards: each suit with each type # To unde...
# Instead of writing it ourselves, let's use a pre-written one from PyCrypto # PyCrypto is the library we'll be using for the project # To start with, let's import the XOR cipher from Crypto.Cipher import XOR # We'll also use their random to get random bits for our key from Crypto.Random import get_random_bytes m = "...
import sys def validate(month, day): halloween = (month == "OCT" and day == 31) christmas = (month == "DEC" and day == 25) return (halloween or christmas) input = sys.stdin.readline().rstrip().split(' ') month = input[0] day = int(input[1]) if (validate(month, day)): print("yup") else: print("nop...
from __future__ import annotations from typing import List class Polynomial: def __init__(self, coeffs: List[float]): self.coeffs = coeffs self.deg = len(coeffs) def __str__(self) -> str: output = "" for i in reversed(range(self.deg)): output += f"{self.coeffs[i]...
from math import floor def recursive_merge_sort(A, p, r): if p >= r: return A else: q = floor((p + r) / 2) recursive_merge_sort(A, p, q) recursive_merge_sort(A, q + 1, r) merge(A, p, q, r) def merge(A, p, q, r): n1 = q - p + 1 n2 = r - q B = A[p:q+1] B...
text = input() words=text.split() wordslen=len(words) letter=0 for l in words: letter+= len(l) print(letter/wordslen)
# Tutorial: "A tour of Data Assimilation methods" # Model: Lorenz-63 # DA Methods: Nudging, 3D-Var, 4D-Var, Particle Filter, EnKF, Hybrid # # Purpose: # Tutorial 1 focuses on generating the nature run, free run, and # Lyapunov Exponents of the nature system, the Lorenz-63 model. # # import numpy as np from class_lor...
#5 - Crie uma função que receba parâmetro uma lista, com valores de qualquer tipo #A função deve imprimir todos os elementos da lista, enumerando - os. imprime_lista = ["abacate", "feijao", "arroz", "laranja", "banana", "carne"] for i,j in enumerate(imprime_lista, 1): print(i,j)
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or len(matrix[0]) == 0: return False def binarySearch(array, target): l...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: ans = None def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if p is Non...
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or len(matrix[0]) == 0: return False def binarySearch(array, target, left=None, rig...
class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ max_reach = 0 index = 0 while index <= max_reach and index < len(nums): jump = index + nums[index] if max_reach < jump: ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ def recursive(head):...
class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # initialize the answer list with only one element ans = [] for num in nums: ans.append([num]) for _ in range(len(nums) - 1): ...
# 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: ans_head = ListNode(0) def recursiveVisit(head): if head is None: ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ self.cache = set() if ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flipEquiv(self, root1, root2): """ :type root1: TreeNode :type root2: TreeNode :rtype...
class Solution: def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) - 1 check_list = [False for x in range(n + 1)] ans = None for element in nums: if check_list[element] == False: ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str ...
class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ # check the length if len(s) == len(t): # use hash table to count the characters is_valid = True hash_table = {} for cha...
# import all the classes from vehicle_class import * from car_class import * from plane_class import * # create 2 vehicle instances vehicle1 = Vehicle(10,200) vehicle2 = Vehicle(2,30) # call methods and attributes to test print('accelerate for vehicle 1 ', 'vehicle 2 cargo size', 'vehicle 1 breaking:') print(vehicle...
#!/usr/bin/env python file = open("students.csv") for line in file: l = line.strip() print("DEBUG: ", l) student = l.split(",") print(student) print("FULLNAME is ", student[0]) print("GENDER is ", student[1]) print("COURSE is ", student[2]) print("DEPARTMENT_CODE is ", student[3]) pr...
num = [2,4,6,8] for i in range(len(num)-1,-1,-1): print(num[i]) num = num + [10,12,14] print("List after append") for i in range(len(num)-1,-1,-1): print(num[i]) print(num)
class EmployeeRecords: def __init__(self, n, i, r): self.n = n self.i = i self.r = r def main(): rec = EmployeeRecords("Mary", 2148, 10.50) print(rec.n,"",rec.i,"",rec.r) main()
def linear_equation(a, b): while True: x=yield print('Expression, %s*x^2 + %s, with x being %s equals %s' % (a,b,x,(a*(x**2)+b))) equation1 = linear_equation(3,4) next(equation1) equation1.send(6)
from math import sqrt num = eval(input()) print("Sqrt is:",sqrt(num))
class cryptography: def encrypt(self, numbers): min_val = min(numbers) inx = numbers.index(min_val) numbers[inx]+=1 result = 1 for item in numbers: result = result * item return result def main(): cry = cryptography() numbers = [1000,999...
class Cell: SIZE = 12 ALIVE = 1 DEAD = 0 def __init__(self, state, rect): if state is not self.ALIVE and state is not self.DEAD: raise Exception("Cell state is excepting a boolean. Given value is: {}".format(state)) self.state = state self.rect = rect self.ne...
# 1.write a python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers inputs = input("your input here:" ) lists = inputs.split(",") print(lists) tuples = tuple(lists) print(tuples) # 2.write a python program to accept a filename from the user...
# 1) Создать класс автомобиля. Создать классы легкового автомобиля # и грузового. Описать в основном классе базовые атрибуты и методы # для автомобилей. Будет плюсом если в классах наследниках # переопределите методы базового класса. class Car: def __init__(self, brand: str, model: str, year: int, max_speed: int)...
## @file menu.py # Source file for the menu object # # Project: Minesweeper # Author: Ayah Alkhatib # Created: 09/08/18 from executive import Executive ## @class Menu # @brief Prints menu and rules; Manages Executive instance class Menu: ## Constructor; initializes class variables # @author: Ayah ...
#https://www.hackerrank.com/challenges/botcleanr/problem #!/usr/bin/python # Head ends here def distance_to_dirt(bot_x, bot_y, board): for x_idx in range(5): for y_idx in range(5): if board[x_idx][y_idx] != 'd': continue dirt_x = x_idx dirt_y = y_idx break ...
from abc import ABC, abstractmethod from typing import Dict, List class BaseTaggingManager(ABC): @classmethod @abstractmethod def get_tags_dict_from_text( cls, plain_text: str ) -> Dict[str, List[str]]: """ Return mapping of words and tags in the next format: ...
# # import itertools # # number_set = set() # # # def add_number(dice, sequence, idx, number): # if idx == len(sequence): # number_set.add(number) # return # # for n in dice[sequence[idx]]: # add_number(dice, sequence, idx+1, number+str(n)) # # # # # # # print([1] + [2]) # # # def soluti...
months, days = ( '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12' ), ('31', '29', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31') for m, d in zip(months, days): for i in range(1, int(d)+1): dd = int(m+str(i).zfill(2)) if 219 <= dd <= 520: sm = 'SPR...
import heapq def minus_arg(node): node.arg1 -= 2 return node class Node: def __init__(self, arg1: int, arg2: str, arr): self.arg1 = arg1 self.arg2 = arg2 self.arr = arr def __lt__(self, other): if self.arg1 < other.arg1: return True elif self.arg1...
def robot(x, y, count, percent): global per if visited[x][y] == True: per += percent return if count == n: return if east: visited[x][y] = True robot(x, y+1, count+1, percent*east) visited[x][y] = False if west: visited[x][y] ...
def mergeSort(arr, p, r): q = int((p + r) / 2) # print("p : {}, r : {}, q : {}".format(p, r, q)) if p < r: mergeSort(arr, p, q) mergeSort(arr, q+1, r) return merge(arr, p, q, r) else: return arr def merge(arr, p, q, r): i = p # 첫번째 배열 시작 j = q+1 # 첫번째 배열 끝 k ...
def switch(arg): if arg == 1: return 0 elif arg == 0: return 1 else: return switch_len = int(input()) switch_list = list(map(int, input().split())) student_num = int(input()) # 1 2 3 4 5 6 7 8 # 0 1 0 1 0 0 0 1 # 남학생 : 스위치 번호가 내가 받은 번호의 배수라면 스위치 변경 # 여학생 : 내가 받은 번호를 중심...
# 재귀 함수 : 자기 자신을 호출하는 함수 # 재귀 호출 : 재귀적 정의(점화식)을 구현하기 위해 사용 # 그래프의 길이 우선 탐색, 백트래킹 시 자주 사용한다. # 기본 개념은 반복, for나 while을 사용하지 않고 반복을 사용할 수 있다. # for i in range(3): # print('hello?') >> 보통의 반복문 # 재귀함수의 조건. 몇번 반복할것인가? # >> 매개변수를 counting하는 조건으로 주어 반복횟수를 조절한다. # count = 0 # def hello(count): # if c...
def is_prime_number(number): for i in range(2, number): if not number % i: return 0 return 1 def encode_num(number, n): if number < n: return str(number) s = encode_num(number//n, n) return s + str(number % n) print(encode_num(11, 2)) def solution(n, k): answer =...
# def bishop(s, e, count): # global max_count # t = 0 # for i in range(s, b_len): # result2 = True # x, y = b_list[i][0], b_list[i][1] # for k in range(len(dx)): # if result2 == False: break # d_x, d_y = dx[k], dy[k] # while 0 <= x + d_x <...
def sort_and_tuple(arr): return tuple(sorted(arr)) def check(coor_1, coor_2, board, flag): n = len(board) move_list = [[(0, -1), (0, 1)], [(-1, 0), (1, 0)]] if flag == 'horizontal': move_list.reverse() move_ver, move_hor = move_list[0], move_list[1] result = [] for move in move_v...
class BSTree: def __init__(self): self.root = None def inorder(self): return self.root.inorder() if self.root else [] def min(self): return self.root.min() if self.root else None def max(self): return self.root.max() if self.root else None # lookup의 입력 인자 : key ...
def solution(board, moves): answer = 0 basket = [] for m in moves: i = 0 while i < len(board): doll1 = board[i][m-1] if doll1 != 0: if not basket: basket.append(doll1) else: doll2 = bas...
import sys sys.stdin = open('1_input.txt', 'r') t = int(input()) for i in range(1, t+1): word = input() word_len = len(word) # print(word_len) result = 'Exist' for j in range(0, word_len//2): # print(word[j], word[word_len-j-1]) if word[j] == '?' or word[word_len-j-1] =...
def get_subset(arr): n = len(arr) result = [] for i in range(1 << n): temp = [] for j in range(n): if i & (1 << j): temp.append(j) temp_arr = arr[:] for idx in temp: temp_arr[idx] = '-' result.append(' '.join(temp_arr)) retu...
"""Simple exercise file where the kid must write code. Control the LED light in the finch robot with this small exercise. The code doesn't run as it is because a kid is supposed to complete the exercise first. NAO will open this file in an editor. """ from exercises.finch.finch import Finch from time import sleep fi...
# -*- coding: utf-8 -*- from sys import stdin PERFECT = 0 ABUNDANT = 1 DEFICIENT = 2 NUMBER_TYPES = { PERFECT: u'Perfect', ABUNDANT: u'Abundant', DEFICIENT: u'Deficient' } def get_divisors(num): """ Get the divisors of a number 'num', except itself :param num: the number to get divisors ...
# Name - Sidharth Raj##### # importing all the necessary libraries # socket library is used to create and handle various sockets # easygui library is used to create gui import socket import random import json from easygui import * request = "GET / HTTP/1.1\r\nHost: \r\n\r\n" # Client function to send the encoded JS...
# -*- coding: utf-8 -*- # @Time : 19-5-20 上午10:34 # @Author : Redtree # @File : insert_shell.py # @Desc : 希尔排序 #----希尔排序---- def dosort(L): #初始化gap值,此处利用序列长度的一般为其赋值 gap = (int)(len(L)/2) #第一层循环:依次改变gap值对列表进行分组 while (gap >= 1): #下面:利用直接插入排序的思想对分组数据进行排序 #range(gap,len(L)):从gap开始 ...
class SnakeDead(Exception): pass class Snake: def __init__(self, pos, x_direction, y_direction): self.body = [pos] self._alive = True self.x_direction = x_direction self.y_direction = y_direction @property def alive(self): return self._alive def iter(sel...
import socket from SocketWrapper import * from sql import * username = "null" password = "null" con_pass = "null" IP = '0.0.0.0' PORT = 8822 incorrect_message = "one of the details is incorrect" class server: def receive_client_request(self): command = self.socket_wrapper.read_with_len() usernam...
def FactorialRecursion(n): ''' 阶乘的递归实现 :param n:正整数 :return:阶乘结果 ''' if n == 1: return 1 else: return n * FactorialRecursion(n - 1) def Factorial_Iter(n): ''' 阶乘的迭代实现 :param n: 正整数 :return: 阶乘结果 ''' result = n for i in range(1, n): result...
import math def search_min_fun(x, fx): min = fx[0] min_x = x[0] for i in range(len(fx)): if fx[i] < min: min = fx[i] min_x = x[i] return min_x, min def passive_search_N(a, b, Eps): return math.ceil((b - a) / Eps - 1) def passive_search_count(N, a, b):...
import argparse import sys import words import frequency import key ENCODE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' class Crib: def __init__(self): self.cribwords = [] def load(self, filename): with open(filename, 'r') as f: for line in f: self.cribwords.append(line...
def insertion_sort(l: list) -> list: if len(l) <= 1: return l # Pick one item, then find the right place in the list to put it in for unsorted in range(len(l)): hold = l[unsorted] i = unsorted - 1 while i >= 0 and hold < l[i]: l[i + 1] = l[i] i -= 1 ...
def alternating_characters(s): temp = s[0] res = 0 for i in s[1:]: if i == temp: res += 1 else: temp = i return res if __name__ == '__main__': with open("testCase/alternating_characters.txt") as f: f.readline() li = f.read().split("\n") f...
class Solution: def convertToBase7(self, num: int) -> str: s = '' neg = False if(num < 0): num *= -1 neg = True while num != 0: s = str(num % 7) + s num = num // 7 if neg == True: s = '-' + s return int(s) s ...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def sortList(self, head: ListNode) -> List...
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def balanceBST(self, root: TreeNode) -> TreeNode: l = self.inorderTraversal(root) start = 0 en...
from typing import List class Solution: def runningSum(self, nums: List[int]) -> List[int]: sumNums = [] for i in range(len(nums)): sumNum = 0 for j in range(i+1): sumNum += nums[j] sumNums.append(sumNum) return sumNums s = Solution() pri...
# Definition for a Node. class Node: def __init__(self, x: int, y: int, next: 'Node' = None, prev: 'Node' = None): self.key = int(x) self.val = int(y) self.next = next self.prev = prev def __str__(self): return "Node key: " + str(self.key) def __repr__(self): ...
from typing import List #TODO class Solution: def search(self, nums: List[int], target: int) -> int: high = len(nums)-1 low = 0 while high >= low: # return self.searchIn(nums, 0, len(nums)-1, target) # def searchIn(self, nums: List[int], low: int, high: int, target: int)...
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: t3 = TreeNode() if (t1 is None) and (t2 ...
def prompt(message, errormessage, isvalid): """Prompt for input given a message and return that value after verifying the input. Keyword arguments: message -- the message to display when asking the user for the value errormessage -- the message to display when the value fails validation isvalid -- ...
marks=int(input("Enter the marks")) if(marks>85 and marks<=100): print("Congrats Your Score A"); elif(marks>60 and marks<=85): print("Congrats Your Score B+"); elif(marks>40 and marks<=60): print("Congrats Your Score B"); elif(marks>30 and marks<=40): print("Congrats Your Score C"); else: print("Oo...
# (8) SUM OF NUMBERS # Michael Manzzella # Oct 11 20:06 # Write a program with a loop that asks the user to enter a series of positive numbers. The user should enter a negative # number to signal the end of the series. After all the positive numbers have been entered, the program should display their # sum. total = ...
# Michael Manzella # 22-Sep-20 # # (1) Bug Collector # A bug collector collects bugs every day for five days. Write a program that keeps a running total of the number of bugs # collected during the five days. The loop should ask for the number of bugs collected for each day, and when the loop is # finished, the p...
print(""" # Crie um programa que leia o nome completo de uma pessoa e mostre: > O nome com todas as letras maiúsculas > O nome com todas as letras minusculas > Quantas letras ao todo (sem considerar os espaços) > Quantas letras tem o primeiro nome """) nome =...
# Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. sal = float(input('Qual o salário do Funcionário? R$ ')) aum = sal + (sal * 15 / 100) print('Um funcionário que ganhava {:.2f}, com 15% de aumento, passa a receber {:.2f} de salário.'.format(sal, aum))