text
stringlengths
37
1.41M
# My name is Sofya. This program computes cost of a beverage. # The program asks for the customer's name. name = input("Hello, what is your name?") if name.isalpha(): print("Welcome,"+name+"!") else: print("Sorry, the name should contain only letters.") exit() # The program asks for the type of a ...
import math class Grocery: def __init__(self): self.items = { 'Banana': {'price': 4, 'stock': 6, 'code':1 }, 'Apple': {'price': 2, 'stock': 0,'code':2 }, 'Orange': {'price': 1.5, 'stock': 32,'code':3}, 'Pear': {'price': 3, 'stock': 15,...
class User: def __init__(self, name, balance ): self.name = name self.balance = balance print(name, balance) def deposit(self, amount): self.balance += amount return self def make_withdrawal(self, amount): if amount > self.balance: return "non su...
# Suppose we have a standard linked list. # Construct an in-place (without extra memory) algorithm # thats able to find the middle node! # ================================================ # Using Bruteforce method means iterating through whole linked list finding the size # and again iterating throgh the linked list ...
# In a given grid, each cell can have one of three values: # the value 0 representing an empty cell; # the value 1 representing a fresh orange; # the value 2 representing a rotten orange. # Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. # Return the minimum number...
# find GCD from given array. # arr = [2,4,6,8] # gcd = 2 def findGCDofArray(arr) -> int: gcd = getGCD(arr[0], arr[1]) for i in range(len(arr)): gcd = getGCD(gcd,arr[i]) return gcd def getGCD(numA:int, numB:int) -> int: while(numB): numA, numB = numB, numA%numB return numA if __na...
# The following iterative sequence is defined for the set of positive integers: # n → n/2 (n is even) # n → 3n + 1 (n is odd) # Using the rule above and starting with 13, we generate the following sequence: # 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 # It can be seen that this sequence (starting at 13 and finishing...
#================================ # Part B: Golden Eggs #================================ # Problem 1 def dp_make_weight(egg_weights, target_weight): """ Find number of eggs to bring back, using the smallest number of eggs. Assumes there is an infinite supply of eggs of each weight, and there is al...
def parse_input(): with open("input1.txt", 'r') as f: return f.read() # Prints the number of the first instruction that lands us at the basement. def find_basement(): string = parse_input() floor = 0 pos = 0 for c in string: if c == '(': pos += 1 floor += 1 ...
mum2=input() flag=0 for i in mum2: if((i=="0") or (i=="1")): pass else: flag=1 break if(flag==0): print("yes") elif(flag==1): print("no")
num1,num2=map(int,input().split()) num1=str(num1) num2=str(num2) print(num1+num2)
vox=input() if(len(vox)==1): if(vox=='a' or vox=='A' or vox=='e' or vox=='E' or vox=='i' or vox=='I' or vox=='o' or vox=='O' or vox=='u' or vox=='U'): print("Vowel") else: print("Consonant") else: print("Invalid")
a3=input() c=0 for i in a3: if(i==" "): c=c+1 print(c+1)
a45=input() flag=1 for i in a45: if(a45.count(i)>1): flag=0 if(flag==1): print("yes") elif(flag==0): print("no")
word=input() length_=len(word) for i in range(0,(length_//2)+1): if(word[i]==word[(length_-1)-i]): i=i+1 else: break if(i>length_/2): print("yes") else: print("no")
nummo1=int(input()) nummo1=str(nummo1) for i in nummo1: if((int(i)%2)!=0): print(i,end=" ")
from random import * import sys ops = ['+', '-', '*', '/'] #basic operations def make_arith_basic(max_vars): num_vars = randint(2, max_vars) n = randint(0, 10) num_vars-=1 expr = " " + str(n) while(num_vars!=0): n = randint(0,10) i = randint(0,3) temp_exp = expr + op...
# Simple calculator # ADD def add(num1, num2): return num1 + num2 # Substract def subtract(num1, num2): return num1 - num2 # Multiply def multiply(num1, num2): return num1 * num2 # Divide def divide(num1, num2): return num1 / num2 print("Please select oper...
# 3.1 Question a) import numpy as np vec1= np.arange(5,10) vec2 = np.arange(3,10,2) print vec1 print vec2 # 3.1 Question b) np.linspace(2,5, num=10) a = np.array([[1,2,3,4,5,6]]) # vecteur original à transformer b = np.reshape(a, (3,2)) # transformation du vecteur a en matrice 2x3 c = np.reshape(b, (2,3)) # tran...
def pro(): name=input('enter your name\n') name=name.upper() print('\n\n\t\t\t\t HELLO %s'%(name)) n = input('y and n') if 'n' in 'y': import bot pro()
def food(): data = ['hi', 'hello', 'who are you', 'i am a software program', 'what is software', 'the programs and other operating information used by a computer' 'ok', 'hmmm', 'what is your age', ...
from typing import List ''' /** * This is the solution of No. 912 problem in the LeetCode, * the website of the problem is as follow: * https://leetcode-cn.com/problems/sort-an-array * <p> * The description of problem is as follow: * ===============================================================================...
# encoding='utf-8' ''' /** * This is the solution of No. 258 problem in the LeetCode, * the website of the problem is as follow: * https://leetcode-cn.com/problems/add-digits/ * * The description of problem is as follow: * ==========================================================================================...
# import os def header(text): # Centering print text: # https://stackoverflow.com/questions/33594958/is-it-possible-to-align-a-print-statement-to-the-center-in-python def center (str): #if we wanted to center based on the os terminal size, # replace 50 with: os.get_terminal_size().columns ...
from animals import Animal from interfaces import IFreshwater, ISwimming class Kikakapu(Animal, IFreshwater, ISwimming): instances = [] def __init__(self, age, name): Animal.__init__(self) IFreshwater.__init__(self) ISwimming.__init__(self) self.instances.append(self) s...
import sys from load import load_numbers from random import randint numbers = load_numbers(sys.argv[1]) def quicksort(values): if len(values) <= 1: return values less_than_pivot = [] greater_than_pivot = [] random_index = randint(0, len(values) - 1) pivot = values[random_index] del values[random_index...
""" * Algorithms: Selection Search """ import random import sys import os from helper.load import load_numbers numbers = load_numbers(sys.argv[1]) def my_selection_sort(values): """My implementation of Selection sort.""" new_array = [] while values: min_v = values[0] min_i = 0 ...
# 2. def combiner(lst): x = [] s = '' num = 0 for i in lst: if isinstance(i, str): s += i elif isinstance(i, (int, float)): num += i return f'{s}{num}' # print(combiner(["apple", 5.2, "dog", 8])) # Add a new property to the Rectangle class named area. It sh...
import datetime import random from questions import Add, Multiply class Quiz: questions = [] answers = [] def __init__(self): question_types = (Add, Multiply) # generate 10 different questions with numbers from 1 to 10 for _ in range(10): num1 = random.randint(1, 15) ...
class Stack: class Frame: def __init__(self, data, next_frame): self.data = data self.next_frame = next_frame def __init__(self): self.items = [] self.head = None self.size = 0 def push(self, data): new_frame = self.Frame(data, self.head) ...
from typing import Dict, List, Tuple Seats = Dict[Tuple[int, int], str] def list_to_dict(data: List[List[str]]) -> Seats: """Convert from a list of lists to a dict of tuples with row/col as the keys and the string seat as the value.""" rows_cols = [(r, c) for r in range(len(data)) for c in range(len(data...
#!/usr/bin/env python import __builtin__ class sublist(list): def __init__(self, data=[]): #super(type(self),self).__init__(data) __builtin__.list(self).__init__(data) l = sublist([1, 2]) print l.items()
from copy import copy, deepcopy class classname1(): value=None def method1(self): pass def __repr__(self): return "repr" class classname2(): pass def get_class_members(klass): ret = dir(klass) if hasattr(klass,'__bases__'): for base in klass.__bases__: ret = ret + get_class_membe...
from lxml import etree root = etree.Element("root", interesting="totally") root.text="Text inside tag" root.tail="text after tag" print(etree.tostring(root, pretty_print=True)) # <root interesting="totally">Text inside tag</root>text after tag
from lxml import etree root = etree.Element("root") root.text="Text inside tag" br = etree.SubElement(root, "br") print root.xpath("br") # http://stackoverflow.com/questions/9233092/using-lxml-and-path-to-parse-xml-but-get-empty-list-if-it-has-xmlns-declaration?rq=1 # http://lxml.de/xpathxslt.html url="http://export...
#Question 1 Two Sum #Given an array of integers num and an integer target #Return indices of the two numbers such that they add up to target #Assume taht each input would have exactly one solution #And you may not use the same element twice def twoSum(nums, target): seen = {} for i, v in enumerate(nums): ...
from abc import ABC, abstractmethod import json class SettingsGood(ABC): instance = None @abstractmethod def __init__(self): pass class _SettingsGood: def __init__(self): self.settings = {} def set(self, key, value): self.settings[key] = value def save(self): f = open('set...
def pairwise(iterable): "For sequence of (a, b, c) yield pairs of (a, b), (b, c), (c, None)." prev = Ellipsis for it in iterable: if prev is not Ellipsis: yield (prev, it) prev = it yield (it, None) def set_union(*sets): # Python's set.union is unfortunately not a class...
class Node: def __init__(self, d): self.data = d self.left = None self.right = None def sortedArrayToBST(arr): if not arr: return None mid = (len(arr))//2 root = Node(arr[mid]) root.left = sortedArrayToBST(arr[:mid]) root.right = sortedArrayToBST(arr[mid+1:]) return root def ...
class Node: def __init__(self, val): self.right = None self.left = None self.val = val def inorder(root): # go to leftmost node while pushing to stack, when no left is available pop and print it and then go to right node and continue stack = [] current = root while True: if current is not None: stack....
# Sentiment analysis with feature engineering based method # using naïve bayes classifier with bag of words features # Author: Jialun Shen # Student No.: 16307110030 import nltk from data_utils import * # Load the dataset dataset = StanfordSentiment() tokens = dataset.tokens() nWords = len(tokens) allWords = list(tok...
import sys def __compare(number1, number2): if len(number1) > len(number2): return 1 elif len(number2) > len(number1): return -1 else: i = 0 while i < len(number1): if int(number1[i]) > int(number2[i]): return 1 elif int(number2[i]) >...
def distribute(group_list, n, m): root, group, size = list(range(m)), [[] for _ in range(n + 1)], [1] * m def find(node): if root[node] != node: root[node] = find(root[node]) return root[node] def union(node1, node2): small, big = tuple(sorted([find(node1), find(node2)]...
class Solution: def divisorGame(self, N: int) -> bool: checked = {1: False} self.check_only(N, checked) return checked[N] def check_only(self, N, checked): if N in checked: return checked[N] result = False for x1 in range(N - 1, 0, -1): i...
import heapq class KthLargest: def __init__(self, k: int, nums: list): self.heap = [] self.k = k for i in nums: if len(self.heap) < k: heapq.heappush(self.heap, i) elif i > self.heap[0]: heapq.heapreplace(self.heap, i) heapq....
def transfer(computers, cables): hours, installed = 0, 1 while installed < cables: installed += installed hours += 1 remaining = max(0, computers - installed) res, rem = divmod(remaining, cables) return hours + res + (rem > 0) if __name__ == "__main__": inp, results = int(input...
def factors(x): result = [] i = 1 while i * i < x: if x % i == 0: result.append(i) i += 1 return result def gcd(big, small): mod = big % small if mod == 0: return small return gcd(small, mod) def find_nums(lcm): f = factors(lcm) biggest = lcm ...
def count_pairs(nums, left, right): nums.sort() result = 0 for i, num in enumerate(nums): start, end, res1 = i + 1, len(nums) - 1, len(nums) while start <= end: mid = (start + end) // 2 if nums[mid] + num >= left: res1, end = mid, mid - 1 e...
def gcd(big, small): mod = big % small if mod == 0: return small return gcd(small, mod) def find_fraction(total): for i in range(total // 2, 0, -1): if gcd(i, total - i) == 1: return str(i) + " " + str(total - i) return "" def solution(inp1): return find_fraction(...
from LeetCode.BST.__tree_node__ import TreeNode class Solution: def is_same_tree(self, p: TreeNode, q: TreeNode) -> bool: if p is None and q is None: return True elif p is None or q is None: return False return p.val == q.val and self.isSameTree(p.left, q.left) and...
import sys def valid_anagram(s, t): counting = {} for i in s: if i not in counting.keys(): counting[i] = 1 else: counting[i] += 1 for j in t: if j not in counting.keys(): return False else: counting[j] -= 1 for k in cou...
def remove_letters(string): removed, count = True, 0 while removed: removed = False best, items = chr(1), {} for i, c in enumerate(string): if i > 0 and ord(c) == ord(string[i - 1]) + 1 or i < len(string) - 1 and ord(c) == ord(string[i + 1]) + 1: if string[i] ...
class Solution: def findCircleNum(self, M: list) -> int: result = 0 visited = set() for i in range(len(M)): if i not in visited: self.do_dfs(M, i, visited) result += 1 return result def do_dfs(self, grid, current, visited): v...
def __equalize__(moves): a = moves["L"] b = moves["R"] c = moves["U"] d = moves["D"] moves["L"] = moves["R"] = min(a, b) moves["U"] = moves["D"] = min(c, d) if moves["U"] == 0 and moves["L"] > 1: moves["L"] = moves["R"] = 1 if moves["R"] == 0 and moves["U"] > 1: moves["U...
from LeetCode.LinkedList.__list_node__ import ListNode def delete_node(node): node.val = node.next.val node.next = node.next.next def solution(l1): delete_node(l1) def main(): inp1 = ListNode(4) inp2 = ListNode(5) inp3 = ListNode(2) inp1.next = inp2 inp2.next = inp3 solution(i...
import sys def array_intersection(nums1, nums2): commons = {} result = [] for i in nums1: commons[i] = 1 for j in nums2: if j in commons.keys(): commons[j] = 2 for k in commons.keys(): if commons[k] == 2: result += [k] return result def sol...
from collections import deque def paint(squares): opposite, n = {"R": "B", "B": "R"}, len(squares) queue, result = deque(), [""] * n + ["R"] for i, square in enumerate(squares): if square != "?": result[i] = square queue.append(i) if not queue: queue.append(len(...
amt = int(input()) if amt > 500: a = amt*0.05 print("5% discount", abs(amt-a)) else: print("No discount", amt)
#Account Generator - v2 student_info = [ { "name": "ROSIE MARTINEZ", }, { "name": "JOE LIU", }, { "name": "SALLY SUE", }, { "name": "B...
import sys import pygame from settings import Settings from ship import Ship from bullet import Bullet class AlienInvasion: """Class to manage a individual game""" def __init__(self): """Initialize the game window / caption ship""" pygame.init() # pygame lib initialize # settings in...
a=int(input("enter 1st num:")) b=int(input("enter 2nd num:")) s=a d=b while(b!=0): r=a%b a=b b=r print("gcd",a) l=s*d/a print("lcm",l)
import argparse """ Documentation Description: Argument is a class with one static method get(), used to read all the arguments from the command line/terminal and read the values and use it in this script, all the arguments related to connecting to the database. Verbose flag used to print ...
import numpy as np import math class PCA(object): """ 1. Standardize the range of input variables so that each onee of them contributes equally to the analysis 2. Transformation is important as PCA is very sensitive to variance 3. """
from utils.metrics_loss import eucledian_distance import numpy as np class k_nearest: # no need to mention object as new-class style Python3 """ K nearest neighbors classifier - The KNN classifier assumes that similar things exist in close proximity of each other - that is objects from a same class wi...
__author__ = 'ryan@barnett.io' def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have be...
#Create animal class class Animal: def __init__(self): # initialise with built in method called __init__(self) - self refers to current class # we declare attributes in our methods self.alive = True self.spine = True self.eyes = True self.lungs = True def breath(self): ...
#!/usr/bin/env python from Tkinter import * import random import Tkinter from Tkinter import * import sys import os import time ''' class App(Frame): def __init__(self,master): Frame.__init__(self,master) master.minimisze(width=500,height=500) self.grid() self.widget() ...
# The project creates a basic skeleton for determining cost price and sales volume # Use the variables listed in the class to change the values and determine the impact from numpy import random as rd import pandas as pd import time as t class amazon_price_structure: # This class is used to calculate the cost of deli...
# counts the repeating element in an array def noCount(nums): c={} count=0 for i in range(len(nums)): for j in range(len(nums)): if nums[i] == nums[j]: count+=1 c[nums[i]]=count count=0 return c ...
""" GameAI.py Created by: D.C. Hartlen Date: 19-Aug-2018 Updated by: Date: Contains the algorithm to allow a computer to always win or draw at a game of tic tac toe. The entirety of the algorithm presented here was developed by Cecil Wobker (https://cwoebker.com/posts/tic-tac-toe). However, I have made chang...
import random def genBoard(): #Generate an empty board return [0,0,0,0,0,0,0,0,0] def printBoard(T): #Print the board in a user-friendly manner if len(T) != 9: return False for i in T: if (i != 0) and (i != 1) and (i != 2): return False msg=[] pos=0 for i in T: if (...
""" Compare two strings A and B, determine whether A contains all of the characters in B. The characters in string A and B are all Upper Case letters. """ def compareStrings(A, B): ss = [0] * 256 tt = [0] * 256 for i in range(len(A)): pos = ord(A[i]) ss[pos] = ss[pos] + 1 for j in ran...
# Given two given arrays of equal length, the task is to find # if given arrays are equal or not. Two arrays are said to be # equal if both of them contain same set of elements, arrang- # -ements (or permutation) of elements may be different though. def is_same(arr1, arr2): if len(arr1) != len(arr2): retu...
# Reverse words in a given string def reverse_string_word(string): temp = '' n = len(string) for i in range(n): c = string[n-1-i] if c == ' ': if temp: print temp, temp = '' else: temp = c + temp if temp: print tem...
import re string1=input() string2=input() for i in string1: if(re.search(string1,string2)): print(int(string1[i]),int(string1[i+1]))
#Add your code here def converToDollar(amount): ruppees=amount*65 totalamount=ruppees-(ruppees*1)/100 return totalamount amount=int(input("Enter the number of dollars:")) total=converToDollar(amount) print(total)
class node: def __init__(self, step): self.step = step self.depth = -1 self.visited = 0 def set_step(self, val): self.step = self.step + val def update(test, val): test.step += val def random(node): node.depth+= 1 if __name__ == '__main__': a = node(3) a....
# 자연수 n의 약수를 출력하는 함수 # 일반적인 코드로 작성하기 n = int(input('n을 입력해주세요 : ')) for i in range(1, n+1): if n % i == 0: print(i) # 입력이 없는 함수로 작성하기 def divisor(): n = int(input('n을 입력해주세요 : ')) for i in range(1,n+1): if n % i == 0: print(i) divisor() # 입력이 있는 함수로 작성하기 def divisorOne(n): ...
# 1부터 5까지의 합 구하기 # i < 5 # 선증가 : i = i + 1 # 후처리 : sum = sum + i i = 1 sum = 1 while i < 5: i = i + 1 sum = sum + i print(f'i={i}, sum={sum}, {i}<5={i<5}') print(f'1부터 5까지 합계 : {sum}')
# 홀수 마방진 n = 5 # 홀수 개수만 입력 arr = [[0]*n for x in range(n)] # 배열 생성 초기화 # 시작을 위한 위치 설정 row = 0 col = n//2 arr[row][col] = 1 # 시작 위치에 1을 넣고 시작 # 행의 오른쪽 끝 열의 상단 끝에 있을 경우 되돌아오기 위해 위치 넣을 변수 x = 0 y = 0 for i in range(2,n*n+1): x = row y = col row = row - 1 # 행 감소 col = col + 1 # 열 증가 i...
# 에라토스체 def is_prime(num): if num <=1 : return False i = 2 while i*i <= num: if num%i ==0: return False i = i + 1 return True print(is_prime(11))
''' Spiral Matrix (https://leetcode.com/problems/spiral-matrix/) Given an m x n matrix, return all elements of the matrix in spiral order. Example 1: [[1,2,3], [4,5,6], [7,8,9]] Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5] Example 2: [[1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12]] Input: matr...
class Data: """ This class holds the data matrix and related function """ def __init__(self): self.__matrix = [] def getMatrix(self): return self.__matrix def setMatrix(self, matrix): self.__matrix = matrix def getAvailableFeatures(self): """ This ...
import random from DecisionTree.DecisionTree.DecisionTree import DecisionTree class EnsembleUtil: """ This is a utility class for performing Ensemble learning such as Bagging/Boosting """ def createBootstrapSamples(self, trainingSet, numBags): """ This function creates 'numBags' boots...
#https://leetcode.com/problems/find-the-celebrity/description/ # The knows API is already defined for you. # @param a, person a # @param b, person b # @return a boolean, whether a knows b # def knows(a, b): class Solution(object): def findCelebrity(self, n): """ :type n: int :rtype: int ...
# class Solution(object): class ListNode(object): def __init__(self, x): self.val = x self.next = None def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ head = None curr_node = ...
#https://leetcode.com/problems/group-anagrams/ class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ """ hold a dictionary 'sorted anagram'-> list of anagrams sort - if in dictionary append to value ...
""" Copyright (C) 2020-2022 Vanessa Sochat. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. """ enter_input = getattr(__builtins__, "raw_input", input) def request_inpu...
import datetime as dt import six if six.PY2: from tkinter import * if six.PY3: from tkinter import * class CountDownTimer: dark = '#333333' white = '#D0D6D3' master = None titleLabel = None countLabel = None footerLabel = None initWidth = None initHeight = None init...
""" Author: Joel Potts Language: Python2.7 Last Edit: 10/25/13 Summary: This program is meant to emulate the learning process of an MCP neuron based off of the Simple Perceptron Learning. """ """ Initialize variables w1,w2 - the weights used on the inputs b - the bias n - the neeta value (learning curve) error - indic...
#!/usr/bin/env python3 import sys def parse(txt): foods = [] for row in txt.strip().split("\n"): words = row.split(" ") ingredients = [] allergens = [] state = 0 for w in words: if state == 0: if w == "(contains": state = ...
#!/usr/bin/env python3 import sys # tokens NUM = 0 ADD = 1 MUL = 2 LPAR = 3 RPAR = 4 EOF = 5 # expression = factor {"+" factor | "*" factor}* # factor = number | "(" expression ")" class Grammar1(object): def __init__(self): self.pos = 0 self.cur = (EOF, None) self.txt = "" def eval(...
totalNums = int(input()) phoneBook={} for i in range(0,totalNums): string = input() Input = string.split(' ') phoneBook[Input[0]]=Input[1] hell = input() while hell != "": if hell in phoneBook: print(hell + "=" + phoneBook[hell]) else: print("Not found") hell = input()
a = 1 b = 10 def test(a): a = a + 1 print(b, "b변수") return a print(a, "1St") a = test(a) print(a, "2nd") def add(a, b): """ add function """ return a + b add.__doc__ = "add function" help(add)
from functools import reduce import operator class Calculator: def __init__(self): print("Turn on Calculator") def fnAdd(self, *arg): print("The result is : %d" % (sum(arg))) def fnMinus(self, *arg): print("The result is : %d" % (reduce(operator.__sub__, arg))) def fnMultipl...
print(1) print('hi guys') a = 'Hello\n' x = 0.2 print(x) str(x) print(str(x)) a = repr('hello\n') print(a) import sys print("Welcome to", "python", sep="-", end="!", file=sys.stderr) import sys help(sys.stderr) #파일 입출력 // Default is Read f = open('file.txt', 'w') # Write f.write('plow deep\nwhile sluggards sleep') ...
from phone_store import PHONES def search_by_props(name,memory,color): phones = [] for phone in PHONES: if phone['name'] == name and phone['memory'] == memory and phone['color'] == color: phones.append(phone) if len(phones) == 0: print("Извините у нас нет в наличии этот телефон...
def findTheDifference(s, t): """ :type s: str :type t: str :rtype: str """ a=list(t) for i in s: if i in t: a.remove(i) a=''.join(a) print(a) return "".join(a) s="abcd" t="aacbde" findTheDifference(s,t)
def maxSubArray(nums): ans=nums[0] sum=nums[0] for i in range(1,len(nums)): sum=max(sum+nums[i],nums[i]) if sum>ans: ans=sum return ans
""" @Author: Brady Miner GPA Calculator: Will calculate n number of grades and return the average GPA. """ print("\nThis program will calculate your GPA based on the number of grades entered.\n" "Valid grades include '+' or '-' symbols.\n" "Invalid grades such as 'S' or 'G' will not be calculated.\n" ...