text
stringlengths
37
1.41M
numberstring = input("please enter comma separated numbers = ") list1 = list(numberstring.replace(',','')) tuple1 = tuple(numberstring.replace(',','')) print(list1) print(tuple1)
import matplotlib.pyplot as plt x = range(1,50) y = [value * 3 for value in x] print("Values of X:") print(*range(1,50)) print("Values of Y (thrice of X):") print(y) plt.plot(x,y) plt.title('X and Y line') plt.show()
# Родительский класс class Car: def __init__(self, speed, color, name, is_police=False): self.speed = int(speed) self.color = color self. name = name self.is_police = is_police def go(self): print('Машина поехала.') def stop(self): print ('Машина остановилась.') def turn(self,direction): print(f'Машина повернула {direction}') def show_speed (self, speed_now): print(f'Текущая скорость {speed_now} км/ч') # дочерние классы class TownCar (Car): def __init__(self, speed, color, name, is_police): super().__init__(speed, color, name, is_police) return def show_speed(self, speed_now): limit = 60 if speed_now > limit: print(f'Текущая скорость {speed_now} км/ч, превышение скорости на {speed_now-limit} км/ч') else: print(f'Текущая скорость {speed_now} км/ч') class SportCar (Car): def __init__(self, speed, color, name, is_police): super().__init__(speed, color, name, is_police) return class WorkCar (Car): def __init__(self, speed, color, name, is_police): super().__init__(speed, color, name, is_police) return def show_speed(self, speed_now): limit = 40 if speed_now > limit: print(f'Текущая скорость {speed_now} км/ч, превышение скорости на {speed_now-limit} км/ч') else: print(f'Текущая скорость {speed_now} км/ч') return class PoliceCar (Car): def __init__(self, speed, color, name, is_police): super().__init__(speed, color, name, is_police=True) return # функция вывода инфо по автомобилю def car_info (car): print(f'Автомобиль марки {car.name}, цвет {car.color}, максимальная скорость {car.speed} км/ч') # создание объектов car1 = TownCar(180, 'черный', 'Mersedes', False) car2 = SportCar(250, 'красный', 'Ferrari', False) car3 = WorkCar(90, 'серый', 'MAN', False) car4 = PoliceCar(200, 'белый', 'Audi', True) # вывод информации car_info(car1) car1.go() car1.show_speed(20) car1.show_speed(90) car1.turn('направо') car1.stop() car_info(car2) car2.go() car2.show_speed(70) car2.show_speed(120) car2.turn('налево') car2.stop() car_info(car3) car3.go() car3.show_speed(55) car3.show_speed(135) car3.turn('направо') car3.stop() car_info(car4) car2.go() car2.show_speed(50) car2.show_speed(168) car2.turn('налево') car2.stop()
import linked_list2 as ll2 import timeit # start time start = timeit.default_timer() linkedList = ll2.LinkedList() for x in range(1,1000): linkedList.insertLast2("Agam") #print("inserting at", x) # stop time stop = timeit.default_timer() print('insertLast2 Time: ', stop - start) # start time start = timeit.default_timer() linkedList2 = ll2.LinkedList() for x in range(1,1000): linkedList2.insertLast("Agam") #print("inserting at", x) # stop time stop = timeit.default_timer() print('insertLast Time: ', stop - start)
# set -> it contains unique elements only i.e. no duplicacy allowed jwel_set = {"bangles","earing","sandles"} print(jwel_set) jwel_set.add("watch") # set can have all items of same datatype or may be different - different datatype items basket = {"Apple","Banana",20, 10.5} print(basket) for item in jwel_set: print(item)
class Node: def __init__(self,data): self.data = data self.link = None class LinkedList: def __init__(self): self.head = None self.tail = None # high time complexity O(n) def insertLast(self, data): # for first element if (self.head == None): self.head = Node(data) return node = self.head while node.link != None: node = node.link node.link = Node(data) # for using insertlast2 on same object self.tail = node.link # low time complexity O(1) def insertLast2(self, data): # for first element if (self.head == None): self.head = Node(data) self.tail = self.head return self.tail.link = Node(data) self.tail = self.tail.link def insertAfter(self, oData, nData): # for first element if (self.head == None): return "empty list" node = self.head nNode = Node(nData) while node != None: if node.data == oData: node.link, nNode.link = nNode, node.link return f"{oData} Found" node = node.link return f"{oData} Not Found" def delete(self, data): print("deleting...", data) if (not self.head): return "empty list" node = self.head if node.data == data: self.head = node.link return f"{data} Found" prev = None while node: if node.data == data: prev.link = node.link return f"{data} Found" prev, node = node, node.link return f"{data} Not Found" def update(self, oData, nData): if (self.head == None): return "empty list" node = self.head while node: if node.data == oData: node.data = nData return "data updated" node = node.link return f"{data} Not Found" def read(self): nextNode = self.head while nextNode: print(nextNode.data, end=" => ") nextNode = nextNode.link print()
# polymorphism # Poly -> many , morphism -> forms # means many forms """ What is Polymorphism : The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different types. """ # Python program to demonstrate in-built poly- # morphic functions # len() being used for a string print(len("geeks")) # len() being used for a list print(len([10, 20, 30])) # A simple Python function to demonstrate # Polymorphism def add(x, y, z = 0): return x + y+z # Driver code print(add(2, 3)) print(add(2, 3, 4))
import linked_list_practice2 as ll3 linkedList = ll3.LinkedList() linkedList.insertLast2("Agam") linkedList.insertLast2("preet") linkedList.insertLast2("singh") linkedList.insertLast2("go") linkedList.insertLast2("for") linkedList.insertLast2("it") linkedList.read() print(linkedList.delete("Agam")) linkedList.read() linkedList.update("singh", "just") linkedList.read()
# boolean -> True or False flag = True print(flag) flag = False print(flag) c = 10 + 50 # return int flag = 10 < 50 # return boolean print(flag) print(10>50) print(10==50) print(10<50) print(10<=50) print(10>=50) print(10<10) print(10>10) print(10<=10) print(10>=10) print(10==10) # == is equality operator print(type(flag)) flag = bool("") #if we put a value in it then it is true else it will be false print(flag) flag = bool(0) print(flag) flag = bool(["apple","banana","waterm","",""]) print(flag)
# file handling deals with files e.g.: Image file, text file, video file, pdf file etc i.e any type of file # so how it works? # to Access a file you need to open it first # to do so we have a function 'open(param1, param2)' with 2 param # param 1 -> name of file / file name with relative/absolute location # param 2 -> access node of file # Types of access mode -> r, a, w, x, t, b # lets start # lets create a file myIntroFile = open("agam_way.txt", "x") # create a file if it already doesn't exist else throw error # after your work completed always close a file myIntroFile.close()
list = input().split('-') for element in list: print(element[0], end='')
cnt = 0 for i in range(int(input())): word = input() cnt += list(word) == sorted(word, key=word.find) print(sorted(word, key=word.find)) print(cnt)
n = int(input()) result = n for i in range(n): word = input() for j in range(1, len(word)): if(word.find(word[j-1]) > word.find(word[j])): result -= 1 break print(result)
print(len("hello world")) #finding a particular character in a string print("hello"[1]) #Dot notation-object.method print("hello".upper()) print("hello".lower()) print("hello".capitalize()) print("hello".count("l")) print("hello".find("l")) print("hello".replace("hello","HELLO")) print("hello".strip("h"))
from collections import deque # bfs function def bfs_shortest_path(graph, start, goal): # keep track of explored nodes explored = [] # keep track of all the paths to be checked queue = deque([[start]]) # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue path = queue.popleft() # get the last node from the path node = path[-1] if node not in explored: neighbours = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) queue.append(new_path) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.append(node) # in case there's no path between the 2 nodes return [] # lengh function def short(graph,start,end): return len(bfs_shortest_path(graph, start, end))-1 # please create a graph and the nodes you want to find, # use function "short" to return length # here is an exmaple graph={'TLKN': ['SADE'], 'AEQB': [], 'SADE': ['TLKN'], 'FZBJ': [], 'MAGK': ['QTGC'], 'BEGA': ['NUVZ'], 'WJOR': ['NUVZ'], 'IJUY': [], 'QTGC': ['MAGK'], 'NUVZ': ['BEGA', 'WJOR']} print(short(graph,'BEGA', 'WJOR'))
# # @lc app=leetcode id=234 lang=python3 # # [234] Palindrome Linked List # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head: ListNode) -> bool: if not head: return True head_list = [] while True: if head.next is None : head_list.append(head.val) break elif head.next is not None : head_list.append(head.val) head = head.next j = len(head_list)-1 for i in range(len(head_list)): if head_list[i] != head_list[j]: return False i += 1 j -= 1 if i > j == True: break return True # @lc code=end
__author__ = 'Meghan' import matplotlib.pyplot as plt import numpy as np from matplotlib import animation import copy f = open('input.txt', 'r') inp = f.read() f.close() def blankgrid(n, m): # n is number of rows, m is number of columns, from day 6 grid = [[0 for j in range(m)] for i in range(n)] return grid def initgrid(s, n, m): grid = blankgrid(n,m) l = s.split('\n') for i in range(n): grid[i] = list(l[i]) return grid def numgrid(grid): size = (len(grid), len(grid[0])) new = blankgrid(size[0],size[1]) for i in range(size[0]): for j in range(size[1]): if grid[i][j] == '#': new[i][j] = 1 else: new[i][j] = 0 return new def count(mat): # from day 6 size = (len(mat),len(mat[0])) # i,j tally = 0 for i in range(size[0]): for j in range(size[1]): if mat[i][j] == 1: tally += 1 return tally def neighbours(grid,lat,long): # given a grid and a position in the grid, returns what state the neighbours are in size = (len(grid),len(grid[0])) if lat == 0 and long == 0: #corners, top left l = [grid[lat+1][long], grid[lat+1][long+1], grid[lat][long+1]] elif lat == 0 and long == size[1]-1: #corners, top right? l = [grid[lat+1][long], grid[lat+1][long-1], grid[lat][long-1]] elif lat == size[0]-1 and long == size[1]-1: #corners, bottom right l = [grid[lat-1][long], grid[lat-1][long-1], grid[lat][long-1]] elif lat == size[0]-1 and long == 0: #corners, bottom left? l = [grid[lat-1][long], grid[lat-1][long+1], grid[lat][long+1]] elif lat == 0: #edges, top? l = [grid[lat+1][long], grid[lat+1][long-1], grid[lat+1][long+1], grid[lat][long-1], grid[lat][long+1]] elif lat == size[0]-1: #edges, bottom? l = [grid[lat-1][long], grid[lat-1][long-1], grid[lat-1][long+1], grid[lat][long-1], grid[lat][long+1]] elif long == 0: #edges, left? l = [grid[lat][long+1], grid[lat-1][long+1], grid[lat+1][long+1], grid[lat-1][long], grid[lat+1][long]] elif long == size[1]-1: #edges, right? l = [grid[lat][long-1], grid[lat-1][long-1], grid[lat+1][long-1], grid[lat-1][long], grid[lat+1][long]] else: #centre l = [grid[lat+1][long+1], grid[lat][long+1], grid[lat+1][long], grid[lat-1][long+1], grid[lat+1][long-1], grid[lat-1][long], grid[lat][long-1], grid[lat-1][long-1]] return l def neighbourson(grid, lat, long): count = 0 l = neighbours(grid, lat, long) for i in l: if i == "#" or i == 1: count +=1 return l, count def switch(grid,mode=0): new = copy.deepcopy(grid) size = (len(grid),len(grid[0])) for i in range(size[0]): for j in range(size[1]): surround = neighbourson(grid,i,j)[1] if grid[i][j] in [1,'#'] and surround in [2,3]: new[i][j] = 1 elif grid[i][j] in [0,'.'] and surround == 3: new[i][j] = 1 else: new[i][j] = 0 if mode == 1: new[0][0] = 1 new[0][size[1]-1] = 1 new[size[0]-1][0] = 1 new[size[0]-1][size[1]-1] = 1 return new def iterswitch(grid,n,mode=0): time = [grid] while n>0: new = switch(grid,mode) time.append(new) grid = new n -= 1 return grid grid = numgrid(initgrid(inp,100,100)) #print(neighbourson(grid,10,10)[1]) #print(count(iterswitch(grid,100,1))) p1 = count(iterswitch(grid,100,0)) p2 = count(iterswitch(grid,100,1)) print("Day 18: \nPart 1: {0} \nPart 2: {1}".format(p1,p2)) #grid = np.array(numgrid(initgrid(inp,100,100))) #x = range(100) #y = range(100) #x, y = np.meshgrid(x, y) #plt.pcolormesh(x, y, grid) #plt.colorbar() #plt.show() #t0 = ".#.#.#\n...##.\n#....#\n..#...\n#.#..#\n####.." #grid0 = initgrid(t0,6,6) #print(numgrid(grid0)) #print(neighbourson(grid0,0,2)) #print(iterswitch(numgrid(grid0),4)) #print(count(iterswitch(numgrid(grid0),4)))
# Given a string of even length, return the first half. So the string "WooHoo" # yields "Woo". # first_half('WooHoo') --> 'Woo' # first_half('HelloThere') --> 'Hello' # first_half('abcdef') --> 'abc' def first_half(str): return str[:len(str) / 2] print(first_half('WooHoo')) print(first_half('HelloThere')) print(first_half('abcdef'))
# Given three ints, a b c, return True if one of b or c is "close" (differing # from a by at most 1), while the other is "far", differing from both other # values by 2 or more. Note: abs(num) computes the absolute value of a number. # close_far(1, 2, 10) --> True # close_far(1, 2, 3) --> False # close_far(4, 1, 3) --> True def close_far(a, b, c): a_b_diff = abs(a - b) a_c_diff = abs(a - c) b_c_diff = abs(b - c) return (a_b_diff <= 1 and (b_c_diff >= 2 and a_c_diff >= 2) or a_c_diff <= 1 and (b_c_diff >= 2 and a_b_diff >= 2)) print(close_far(1, 2, 10)) print(close_far(1, 2, 3)) print(close_far(4, 1, 3))
# Given a string, we'll say that the front is the first 3 chars of the string. # If the string length is less than 3, the front is whatever is there. Return # a new string which is 3 copies of the front. front3('Java') --> 'JavJavJav' front3('Chocolate') --> 'ChoChoCho' front3('abc') --> 'abcabcabc' def front3(str): front = str[:3] return front+front+front print(front3('Java')) print(front3('Chocolate')) print(front3('abc'))
# Given a non-negative number "num", return True if num is within 2 of a # multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) # is 2. See also: Introduction to Mod # near_ten(12) --> True # near_ten(17) --> False # near_ten(19) --> True def near_ten(num): return (abs(num % 10 - 10) <= 2 or (num % 10) <= 2) print(near_ten(12)) print(near_ten(17)) print(near_ten(19))
# The number 6 is a truly great number. Given two int values, a and b, return # True if either one is 6. Or if their sum or difference is 6. # love6(6, 4) --> True # love6(4, 5) --> False # love6(1, 5) --> True def love6(a, b): return (a == 6 or b == 6 or (abs(a-b) == 6) or (a+b == 6)) print(love6(6, 4)) print(love6(4, 5)) print(love6(1, 5))
# You and your date are trying to get a table at a restaurant. The parameter # "you" is the stylishness of your clothes, in the range 0..10, and "date" is # the stylishness of your date's clothes. The result getting the table is # encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very # stylish, 8 or more, then the result is 2 (yes). With the exception that if # either of you has style of 2 or less, then the result is 0 (no). # Otherwise the result is 1 (maybe). # date_fashion(5, 10) --> 2 # date_fashion(5, 2) --> 0 # date_fashion(5, 5) --> 1 def date_fashion(you, date): if (you <= 2 or date <= 2): return 0 elif (you >= 8 or date >= 8): return 2 else: return 1 print(date_fashion(5, 10)) print(date_fashion(5, 2)) print(date_fashion(5, 5))
# Return True if the string "cat" and "dog" appear the same number of times # in the given string. # cat_dog('catdog') --> True # cat_dog('catcat') --> False # cat_dog('1cat1cadodog') --> True def cat_dog(str): return (str.count("cat") == str.count("dog")) print(cat_dog('catdog')) print(cat_dog('catcat')) print(cat_dog('1cat1cadodog'))
import turtle num_pts = 5 #number sides to your drawing! for i in range (num_pts): turtle.left(360/num_pts) turtle.forward(100) print(num_pts) turtle.mainloop()
interest_rate_pa = 279.83 def calculate_interest_per_month(): loan_amount = int(input("Kolik si chces pujcit penez?")) interest_per_month = loan_amount / 100 * interest_rate_pa / 12 return interest_per_month def calculate_month_payment(interest_per_month): month_payment = (loan_amount/12) + interest_per_month return month_payment def calculate_total_costs(interest_per_month): number_of_months = int(input("Kolik mesicu chces splacet?")) total_costs = interest_per_month * number_of_months return total_costs
""" To modify this program, please head to the ConsoleCommmands module for instructions. Things that you may modify in this module: - Initial print in start() - environmentPrompt() Minimum files needed for the Console API: - Console.py - ConsoleCommands.py - Exceptions.py - ExitCmd.py - HelpCmd.py """ from Console_API import ConsoleCommands class Console: # All Commands used within the console. Must extend AbstractCommand # commands = ConsoleCommands.commands # File to operate on # file = None # Appending or Overwriting Signal# appendMode = None """ Initiates the console environment """ def start(self): print('Welcome to the Game Modding Database! Written by yours truly, Lan! Enter "help" to display all commands') while True: userStr = input(self.environmentPrompt() + ' ') argv = self.parse(userStr) self.exec(*argv) """" Attempts to execute a command from arguments passed from the user """ def exec(self, *argv): # We better have any arguments to execute them if argv: # Create the appropriate command based on args[0] cmd = None name = argv[0] for command in self.commands: if name == command.getName(): cmd = command if not cmd: print("Command %s does not exist" % name) else: # Execute the specific command's action, and pass it the rest of the args cmd.exec(*argv[1:]) """ Modify this to change the applications user prompt text. """ def environmentPrompt(self): return "GMDB@%s>" % (self.file.name) """ Parses space delimited elements from a string to a list. If there is text between quotes '"', all of that text is captured as one element """ def parse(self, s): args = [] temp = "" openQuotes = False for c in s.strip(): if c.isspace() and not openQuotes: args.append(temp) temp = "" elif c != '"': temp += c elif c == '"': openQuotes = not openQuotes if temp: args.append(temp) return args
import time print(time.gmtime(0)) # 0 is default oldest date # time.struct_time(tm_year=1970, # tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0) print(time.localtime()) # no arguments passed thus it takes today's date # time.struct_time(tm_year=2020, # tm_mon=10, tm_mday=20, tm_hour=22, tm_min=28, tm_sec=23, tm_wday=1, tm_yday=294, # tm_isdst=1) print(time.time()) # number of seconds since the first of 1970 # 1603247303.650089 print() time_here = time.localtime() print(time_here) # time.struct_time(tm_year=2020, tm_mon=10, # tm_mday=20, tm_hour=22, tm_min=33, tm_sec=20, tm_wday=1, tm_yday=294, tm_isdst=1) print("Year:", time_here[0], time_here.tm_year) # Year: 2020 2020 print("Month:", time_here[1], time_here.tm_mon) # Month: 10 10 print("Day:", time_here[2], time_here.tm_mday) # Day: 20 20 print() # measure how fast you press enter after it tells you when to press enter from time import time as my_timer import random input("Please enter to start") wait_time = random.randint(1, 6) time.sleep(wait_time) start_time = my_timer() input("Please enter to stop ") end_time = my_timer() print("Started at " + time.strftime("%X", time.localtime(start_time))) # Started at 22:39:47 print("Ended at " + time.strftime("%X", time.localtime(end_time))) # Ended at 22:39:49 print("Your reaction time was {} seconds ".format( end_time - start_time)) # Your reaction time was 1.9579870700836182 seconds
if __name__ == '__main__': a = int(input()) b = int(input()) add = str(a + b) sub = str(a - b) mul = str(a * b) print(add + "\n" + sub + "\n" + mul)
#!/bin/python3 import math import os import random import re import sys # Complete the climbingLeaderboard function below. def climbingLeaderboard(scores, alice): distinct_scores = list(set(scores)) distinct_scores.sort() ret = [] i = 0 for alice_score in alice: if alice_score >= distinct_scores[-1]: ret.append(1) else: while alice_score >= distinct_scores[i]: i += 1 if i >= len(distinct_scores): break ret.append(len(distinct_scores) + 1 - i) return ret if __name__ == '__main__': scores = [[100,100,50,40,40,20,10],[100,90,90,80,75,60]] alice = [[5,25,50,120],[50,65,77,90,102]] for i in range(2): print(climbingLeaderboard(scores[i], alice[i]))
if __name__ == '__main__': n = int(input()) for num in range(n): print (str(num * num))
#!/bin/python3 import math import os import random import re import sys # Complete the utopianTree function below. def utopianTree(n): height = 1 i = 0 while i <= n: if i > 0: if i % 2 != 0: height *= 2 else: height += 1 i += 1 return height if __name__ == '__main__': lst = [0,1,4] for i in range(len(lst)): result = utopianTree(lst[i]) print(result)
def print_formatted(number): output = "" fmt = len(format(number, 'b')) for i in range(number): num = i + 1 dec = str(num) octa = format(num, 'o') hexa = format(num, 'x').upper() bina = format(num, 'b') output = output + dec.rjust(fmt) + " " + octa.rjust(fmt) + " " + hexa.rjust(fmt) + " " + bina.rjust(fmt) + "\n" print(output) if __name__ == '__main__': n = int(input()) print_formatted(n)
n = int(input()) sum = 0 for i in range(1, n-1): if i % 3 and i % 5: sum+=1 print(sum)
# CUAL ES LA SALIDA side = int(input("Ingrese un valor entero:")) for x in list(range(side)) + list(reversed(range(side-1))): print('{: <{w1}}{:*<{w2}}'.format('', '', w1=side-x-1, w2=x*2+1))
import time def test(n): lst = [] print time.strftime('%H:%M:%S') #for i in range(10000*n): # lst = lst + [i] # # lst.append(i) lst = list(range(10000*n)) # lst = [i for i in range(10000*n)] print time.strftime('%H:%M:%S') print lst[:30] # return lst # return list(rannge(10000*n) test(10)
from trees.node import Node from typing import List from collections import deque def depth_first_in_order(root: Node) -> List: res = [] def recurse(node): if node is not None: recurse(node.left) res.append(node.data) recurse(node.right) recurse(root) return res def depth_first_pre_order(root: Node) -> List: return [] def depth_first_post_order(root: Node) -> List: return [] def breadth_first(root: Node) -> List: res, q = [], deque() q.append(root) while len(q) > 0: el = q.popleft() if el.left is not None: q.append(el.left) if el.right is not None: q.append(el.right) res.append(el.data) return res
import unittest from graphs.dijkstra import find_shortest_path class TestDjikstra(unittest.TestCase): empty_graph = {} graph = { 'A': [('B', 2), ('C', 1), ('D', 3)], 'B': [('A', 2), ('G', 3), ('H', 2), ('I', 4)], 'C': [('A', 1), ('D', 2), ('I', 2)], 'D': [('A', 3), ('C', 2), ('E', 2), ('F', 4)], 'E': [('D', 2), ('F', 1)], 'F': [('D', 4), ('E', 1), ('K', 2), ('M', 5)], 'G': [('B', 3)], 'H': [('B', 2), ('I', 1)], 'I': [('B', 4), ('C', 2), ('H', 1), ('J', 2)], 'J': [('I', 2), ('K', 1), ('L', 3)], 'K': [('F', 2), ('J', 1), ('L', 3)], 'L': [('J', 3), ('K', 3), ('M', 2)], 'M': [('F', 5), ('L', 2)] } def test_shortest_path_from_to_same_node(self): self.assertEqual(['A'], find_shortest_path(self.graph, 'A', 'A')) def test_shortest_path_from_to_non_existing_nodes(self): self.assertEqual([], find_shortest_path(self.graph, 'A', 'X')) def test_shortest_path_from_to_valid_nodes(self): self.assertEqual(['A', 'C', 'I', 'J', 'L'], find_shortest_path(self.graph, 'A', 'L')) if __name__ == "__main__": unittest.main() # python -m unittest discover test/graphs -v
from typing import List, Set, Dict, Tuple, Optional from math import inf def find_shortest_path(graph: Dict[str, List[Tuple[str, int]]], start: str, target: str): if start == target: return [start] vertices: List[str] = list(graph.keys()) if not vertices or start not in vertices or target not in vertices: return [] # print("find_shortest_path({},{},{})".format(graph, start, target)) still_need_to_be_visited: Dict[str, bool] = {vertex: True for vertex in vertices} paths: Dict[str, Tuple[int, str]] = {vertex: (0 if vertex == start else inf, None) for vertex in vertices} while any(still_need_to_be_visited.values()): v = get_lowest_cost_unvisited_vertex(paths, still_need_to_be_visited) # print("visiting {}".format(v)) v_cost, v_origin = paths[v] for neighbour, cost_to_neighbour in graph[v]: neighbour_current_cost, neighbour_current_origin = paths[neighbour] if v_cost + cost_to_neighbour < neighbour_current_cost: paths[neighbour] = (v_cost + cost_to_neighbour, v) still_need_to_be_visited[v] = False res = [target] while start not in res: *xx, last = res res.append(paths[last][1]) # print("solution is {}".format(res[::-1])) return res[::-1] def get_lowest_cost_unvisited_vertex(graph: Dict[str, Tuple[int, str]], still_need_to_be_visited: Dict[str, bool]) -> str: graph_items = [item for item in graph.items() if still_need_to_be_visited[item[0]] is True] graph_items.sort(key=lambda elem: elem[1][0]) return graph_items[0][0]
import unittest from strings.calculate_expression import calculate class TestCalculateExpression(unittest.TestCase): def test_empty_string(self): self.assertEqual(calculate(""), 0) def test_simple_expression(self): self.assertEqual(calculate("1+2+3"), 6) def test_long_expression(self): self.assertEqual(calculate("1+4+(7-(1-5))+5"), 21) def test_long_expression_with_larger_ints(self): self.assertEqual(calculate("-23+12+(405-399-(123-125+10))-1111"), -1124) if __name__ == "__main__": unittest.main() # python -m unittest discover test/strings -v
from .abstract_algorithm import AbstractAlgorithm class OddOccurrences(AbstractAlgorithm): def solution(self, A, debug): element_set = set() print(A) for e in A: if e in element_set: element_set.discard(e) else: element_set.add(e) print('Element : {0} -> Set : {1}'.format(e, element_set)) return list(element_set)[0] def execute(self): self.process([9, 3, 2, 3, 9, 7, 2], 7)
import unittest from src.model.customer import Customer from src.model.product import Product from src.model.shoppingcart import ShoppingCart CUSTOMER = Customer("test") PRICE = 100 PRODUCT = "T" class ShoppingCartTest(unittest.TestCase): def test_should_calculate_price_with_no_discount(self): products = [Product(PRICE, "", PRODUCT)] cart = ShoppingCart(CUSTOMER, products) order = cart.checkout() self.assertEqual(100.00, order.total) def test_should_calculate_loyalty_points_with_no_discount(self): products = [Product(PRICE, "", PRODUCT)] cart = ShoppingCart(CUSTOMER, products) order = cart.checkout() self.assertEqual(20, order.loyalty_points) def test_should_calculate_price_with_10_percent_discount(self): products = [Product(PRICE, "DIS_10_ABCD", PRODUCT)] cart = ShoppingCart(CUSTOMER, products) order = cart.checkout() self.assertEqual(90.00, order.total) def test_should_calculate_loyalty_points_with_10_percent_discount(self): products = [Product(PRICE, "DIS_10_ABCD", PRODUCT)] cart = ShoppingCart(CUSTOMER, products) order = cart.checkout() self.assertEqual(10, order.loyalty_points) def test_should_calculate_price_with_15_percent_discount(self): products = [Product(PRICE, "DIS_15_ABCD", PRODUCT)] cart = ShoppingCart(CUSTOMER, products) order = cart.checkout() self.assertEqual(85.00, order.total) def test_should_calculate_loyalty_points_with_15_percent_discount(self): products = [Product(PRICE, "DIS_15_ABCD", PRODUCT)] cart = ShoppingCart(CUSTOMER, products) order = cart.checkout() self.assertEqual(6, order.loyalty_points) def test_should_calculate_price_with_BUY_2_GET_1(self): products = [Product(PRICE, "BUY_2_GET_1_ABCD", PRODUCT), Product(PRICE, "BUY_2_GET_1_ABCD", PRODUCT), Product(PRICE, "BUY_2_GET_1_ABCD", PRODUCT), Product(PRICE, "BUY_2_GET_1_EFGH", PRODUCT), Product(PRICE, "BUY_2_GET_1_EFGH", PRODUCT)] cart = ShoppingCart(CUSTOMER, products) order = cart.checkout() self.assertEqual(400, order.total) def test_should_add_product(self): new_product = [Product(PRICE, "", PRODUCT)] products = [Product(PRICE, "DIS_10_ABCD", PRODUCT)] cart = ShoppingCart(CUSTOMER, products) cart.add_product(new_product) order = cart.checkout() self.assertEqual(30, order.loyalty_points) self.assertEqual(190, order.total) def test_should_delete_product(self): del_product = Product(PRICE, "", PRODUCT) products = [Product(PRICE, "DIS_10_ABCD", PRODUCT), Product(PRICE, "", PRODUCT), Product(PRICE, "", PRODUCT)] cart = ShoppingCart(CUSTOMER, products) order = cart.checkout() self.assertEqual(50, order.loyalty_points) self.assertEqual(290, order.total) cart.delete_product(del_product) order = cart.checkout() self.assertEqual(10, order.loyalty_points) self.assertEqual(90, order.total) if __name__ == '__main__': # verbosity=*:默认是1;设为0,则不输出每一个用例的执行结果;2-输出详细的执行结果 unittest.main(verbosity=2)
#program for factorial n=eval(input("Enter The No")) fac=1 for i in range(1,n+1): fac=fac*i print("factorial is",fac)
#global variables #board board=[" "," "," ", " "," "," ", " "," "," "] # is game over or not game_not_over=True winner=[None] #display board def display_board(): print("-|1|--|2|--|3|-") print("[ "+board[0]+" ][ "+board[1]+" ][ "+board[2]+" ]") print("-|4|--|5|--|6|-") print("[ " + board[3] + " ][ " + board[4] + " ][ " + board[5] + " ]") print("-|7|--|8|--|9|-") print("[ " + board[6] + " ][ " + board[7] + " ][ " + board[8] + " ]") print("-|-|--|-|--|-|-") #player how plays first it is 0 player="O" # main method def play_game(player,game_not_over): display_board() while game_not_over: handle_turn(player) player=flip_palyer(player) game_not_over=check_if_over(game_not_over) # print(game_not_over) def handle_turn(player): position=input("Choose a position to put your peace:") if((not validation_for_input_number(position)) ): print("position wrong enter valid position") return position=int(position)-1 if(board[position]!=' '): print('postion was already taken ') return board[position]=player display_board() #chewck if win def check_if_win(game_is_over): check1=check_if_equal(0,1,2) check2 = check_if_equal(3, 4, 5) check3 = check_if_equal(6, 7, 8) check4 = check_if_equal(0, 3, 6) check5 = check_if_equal(1, 4, 7) check6 = check_if_equal(2, 5, 8) check7 = check_if_equal(0, 4, 8) check8 =check_if_equal(6,4,2) if( check1 or check2 or check3 or check4 or check5 or check6 or check7 or check8 ): game_not_over=False else: game_not_over=True return game_not_over def check_if_equal(a,b,c): if(board[a]==board[b] and board[b]==board[c] and board[a]!=" "): print(' the winner is ' + board[a]) return board[a]==board[b] and board[b]==board[c] and board[a]!=" " #check where we tie def check_if_tie(game_not_over): if(board[0]!=" " and board[1]!=" " and board[2]!=" " and board[3]!=" " and board[4]!=" " and board[5]!=" " and board[6]!=" " and board[7]!=" " and board[8]!=" "): print(board[0]) game_not_over=False print("The game was a draw") return game_not_over #flip the players def flip_palyer(player): if(player=="O"): player="X" else: player="O" return player #check if the game is over def check_if_over(game_not_over): if(not (check_if_tie(game_not_over)) or not (check_if_win(game_not_over))): game_not_over=False else: game_not_over=True return game_not_over def validation_for_input_number(num): if (num=='1' or num=='2' or num =='3' or num=='4' or num=='5' or num=='6' or num=='7' or num=='8'or num=='9' ): return True else : return False #start very thing play_game(player,game_not_over) print(" thank you for playing") #play game #handle turn #check win #check rows #check columns #check diaganal #check tie #flip player
def get_sum(a , b): return a+b my_sum = get_sum(10,4) print(my_sum) def get_sum2 (a, b, c): return a+b+c my_sum2 = get_sum2(7.8,3.1, 2.2) print(my_sum2) def my_function (var_1, var_2): print(var_1) print(var_2) my_function(3,"abc") def my_function2 (var_1, var_2, var_3): print(var_1) print(var_2) print(var_3) my_function2(4, 6.3, "lol") my_function2(4654, 65, 767) my_function2(5, 65, "sfs") def get_divide(a,b,c): return a/b/c my_divide = get_divide(30, 5, 2) print(my_divide) def my_special_function (my_var): if my_var < 0: print("negative") else: print("pozitive") my_special_function(-3) my_special_function(7)
#通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。 #所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。 #要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator: L=[x*x for x in range(10)] print(L) g = (x * x for x in range(10)) print(g) #创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator。 #如果要一个一个打印出来,可以通过next()函数获得generator的下一个返回值 print(next(g)) g = (x*x for x in range(10)) for n in g: print(n) #斐波拉契数列用列表生成式写不出来,但是,用函数把它打印出来却很容易 def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 return 'done' fib(6) # 赋值语句: # a, b = b, a + b # 相当于: # t = (b, a + b) # t是一个tuple # a = t[0] # b = t[1] #上面的函数和generator仅一步之遥。要把fib函数变成generator,只需要把print(b)改为yield b就可以了 def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done' f = fib(6) print(f) #如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator #这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。 # 而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。 #举个简单的例子,定义一个generator,依次返回数字1,3,5: def odd(): print('step 1') yield 1 print('step 2') yield(3) print('step 3') yield(5) #调用该generator时,首先要生成一个generator对象,然后用next()函数不断获得下一个返回值: o = odd() next(o) next(o) next(o) # 可以看到,odd不是普通函数,而是generator,在执行过程中,遇到yield就中断,下次又继续执行。执行3次yield后,已经没有yield可以执行了,所以,第4次调用next(o)就报错。 # # 回到fib的例子,我们在循环过程中不断调用yield,就会不断中断。当然要给循环设置一个条件来退出循环,不然就会产生一个无限数列出来。 # # 同样的,把函数改成generator后,我们基本上从来不会用next()来获取下一个返回值,而是直接使用for循环来迭代: for n in fib(6): print(n) #但是用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中: g = fib(6) while True: try: x = next(g) print('g:', x) except StopIteration as e: print('Generator return value: ', e.value) break
# 使用type() # 首先,我们来判断对象类型,使用type()函数: # # 基本类型都可以用type()判断 print(type(123)) print(type('abc')) print(abs) # 判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量: import types def fn(): pass print(type(fn) == types.FunctionType) print(type(abs) == types.BuiltinFunctionType) print(type(lambda x: x) == types.LambdaType) type(((x for x in range(10))) == types.GeneratorType) # 使用isinstance() # 对于class的继承关系来说,使用type()就很不方便。我们要判断class的类型,可以使用isinstance()函数。 # 上一章已经很明确了 # 能用type()判断的基本类型也可以用isinstance()判断: print(isinstance('a', str)) print(isinstance(123, int)) print(isinstance(b'a', bytes)) # 并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple: print(isinstance([1, 2, 3], (list, tuple))) print(isinstance((1, 2, 3), (list, tuple))) # 使用dir() # 如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法: print(dir('ABC')) # 类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的: print(len('abc')) print('abc'.__len__()) # 我们自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法 class MyDog(object): def __len__(self): return 100 dog = MyDog() print(len(dog)) # 剩下的都是普通属性或方法,比如lower()返回小写的字符串: print('ABC'.lower()) # 仅仅把属性和方法列出来是不够的,配合getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态 class MyObject(object): def __init__(self): self.x = 9 def power(self): return self.x * self.x obj = MyObject() print(hasattr(obj, 'x')) # 有属性x吗 setattr(obj, 'y', 19) # 设置一个属性'y' print(hasattr(obj, 'y')) print(getattr(obj, 'y')) # 获取属性'y' # 如果试图获取不存在的属性,会抛出AttributeError的错误: # getattr(obj, 'z') # 获取属性'z' # 可以传入一个default参数,如果属性不存在,就返回默认值 getattr(obj, 'z', 404) # # 获取属性'z',如果不存在,返回默认值404 # 获得对象的方法: print(hasattr(obj, 'power')) # 有属性'power'吗 print(getattr(obj, 'power')) # 获取属性'power' fn = getattr(obj, 'power') # 获取属性'power' 并赋值到变量fn fn # fn指向obj.power print(fn()) # 并调用fn()与调用obj.power()是一致的
# 由于Python是动态语言,根据类创建的实例可以任意绑定属性。 # 给实例绑定属性的方法是通过实例变量,或者通过self变量: class Student(object): def __init__(self, name): self.name = name s = Student('Bob') s.score = 90 # 但是,如果Student类本身需要绑定一个属性呢?可以直接在class中定义属性,这种属性是类属性,归Student类所有: class Student(object): name = 'Student' # 当我们定义了一个类属性后,这个属性虽然归类所有,但类的所有实例都可以访问到。来测试一下: s = Student() # 创建实例 print(s.name) # 打印name属性, 因为实例中并没有name属性,所以会继续查找clas的name的属性 print(Student.name) # 打印类的name属性 s.name = 'Michael' # 给实例绑定name属性 print(s.name) print(Student.name) # 但是类属性并未消失,用Student.name任然可以访问 print(s.name) del s.name # 删除实例的name属性 print(s.name) # 再次调用,由于市里的name属性没有找到,类的name属性就找到了 # 从上面的例子可以看出,在编写程序的时候,千万不要对实例属性和类属性使用相同的名字,因为相同名称的实例属性将屏蔽掉类属性,但是当你删除实例属性后,再使用相同的名称,访问到的将是类属性。
# 命名关键字参数 # 对于关键字参数,函数的调用者可以传入任意不受限制的关键字参数。至于到底传入了哪些,就需要在函数内部通过kw检查。 def person(name, age, **kw): if 'city' in kw: # 有city参数 pass if 'job' in kw: # 有job参数 pass print('name:', name, 'age:', age, 'other:', kw) # 但是调用者仍可以传入不受限制的关键字参数 person('Jack', 24, city='Beijing', addr='Chaoyang', zipcode=123456) # 命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数。 def person(name, age, *, city, job): print(name, age, city, job) person('Jack', 24, city='Beijing', job='Engineer') # 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了: def person(name, age, *args, city, job): print(name, age, args, city, job) # person('Jack', 24, 'Beijing', 'Engineer') TypeError # 由于调用时缺少参数名city和job,Python解释器把这4个参数均视为位置参数,但person()函数仅接受2个位置参数。 # 命名关键字参数可以有缺省值,从而简化调用: def person(name, age, *, city='Beijing', job): print(name, age, city, job) person('Jack', 24, job='Engineer') person('Jack', 24, city='ShangHai', job='play') person('Jack', 24, job='play2', city='ShangHai') # 使用命名关键字参数时,要特别注意,如果没有可变参数,就必须加一个*作为特殊分隔符。如果缺少*,Python解释器将无法识别位置参数和命名关键字参数: def person(name, age, city, job): # 缺少 *,city和job被视为位置参数 pass
#def main(): for row in range(4): for col in range(7): if col==0 or col==6 or col==1 or col==5: #if col==0 or col==6 or (col==1 and row==0) or (col==2 and row==0) or (col==3 and row==0) or (col==4 and row==0) or (col==5 and row==0) or (col==6 and row==0): print ("*",end="") else: print (end=" ") print () #if __name__=='__main__': # main()
''' def factorial(number): result =1 while (number != 1): result = result * number number -=1 return result def recursiveFactorial(number): if (number) def main(): num = eval(input("Enter the Number:")) print(factorial(num)) if __name__=='__main__': main() def factorial(number): fact = -1 if number > 0: if number <3: fact=number else: fact=1 while number !=1: fact = fact*number number -=1 print (fact) if __name__=='__main__': factorial(5) ''' def RecursiveFactorial(number): if number == 0 : return 1 return number * RecursiveFactorial(number-1) print (RecursiveFactorial(5))
def verbing(input_str): if len (input_str)<3: return input_str elif input_str[-3:]=='ing': return input_str[:-3]+'ly' else return input_str + 'ing' def main(): input_str=input("Enter string which is to be verbed") output_str=verbing (input_str) print ("ver of {} is {} .format (input_str,output_str)) if __name__=='__main__': main() #ba**ble input_str[0]+ input_str[1:].replace(input_str[0],replace_char)
def row_sum_odd_numbers(n): odd_numbers = [[-1]] for i in range(n): odd = [odd_numbers[-1][-1]+2] for j in range(i): odd.append(odd[-1]+2) odd_numbers.append(odd) return sum(odd_numbers[n]) # return n ** 3 if __name__ == "__main__": print(row_sum_odd_numbers(7))
# Created a simple loop that checks to see if a number is odd and prints them up to 100. for i in range(0, 100): if i % 2 != 0: print(i) i += 1
def digitstoletters(n): ''' takes an integer and returns a string that is the name of the number in words ''' d=dict() d={0:"Zero",1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine"} ans="" for i in str(n): ans+=d[int(i)]+" " return ans def main(): x=int(input("Enter a Number :")) print("You entered : ",digitstoletters(x)) if __name__=="__main__": main()
def permute(lst1,lst2=[],k=0,pos=0): """ Supposed to print all possible permuations of lst1 """ lst2.insert(pos,lst1[k]) if len(lst2)==len(lst1): print(lst2) else: permute(lst1,lst2,k+1,pos) lst2.remove(lst1[k]) if pos< k: permute(lst1,lst2,k,pos+1)
def wordsf(file1): ''' Takes file and displayes no. of words in it ''' f=open(file1,"r") lines=f.read() lines=lines.split() f.close() return len(lines) def main(): n=input("Enter name of file : ") print(wordsf(n)) if __name__=="__main__": main()
def inverse(): try: num=input('Enter the number: ') num=float(num) inverse=1.0/num except ValueError: print('ValueError') except TypeError: print('TypeError') except ZeroDivisionError: print('ZeroDivisionError') except: print('Any other Error') else: print(inverse) finally: print("Function inverse completed\n\n") def main(): inverse() inverse() inverse() inverse() inverse() if __name__=="__main__": main()
#!/opt/rh/rh-python36/root/usr/bin/python3 tempCel=float(input("Digite um valor de temperatura em Graus Celsius: ")) tempFah=((tempCel *1.8)+32) print("A temperatura em Fahrenheit é: ",tempFah)
#!/opt/rh/rh-python36/root/usr/bin/python3 raio=float(input('Digite o raio do circulo: ' )) pi=float(3.141592) area=float(pi*(raio*raio)) print('A área do círculo é: ') print(area)
# Time Complexity:O(n*2) # Space complexity: O(1) # Insertion sort takes maximum time to sort if elements are sorted in reverse order. # And it takes minimum time (Order of n) when elements are already sorted. def insertion_sort(nums): for i in range(len(nums)): j = i while j>0 and nums[j-1] > nums[j]: swap(nums,j,j-1) j = j - 1 return nums # To swap the numbers def swap(nums, i, j): temp = nums[i] nums[i] = nums[j] nums[j] = temp if __name__ == "__main__": nums = [5,4,3,2,1] print(insertion_sort(nums))
class Student: school = " La Masia" def __init__(self, name, school): self.name = name self.school = school self.marks = [] def average(self): # self takes in the object try: return sum(self.marks)/ len(self.marks) except: ArithmeticError def go_to_school(self): return self.name + " is going to " +self.school @staticmethod def schools(): # Doesnt take any objects because it is a static method. return "I am going to school" @classmethod def schoolname(cls): print("The school name is" +cls.school) Harshith = Student("Harshith", "SJSU") Harshith.marks.append(93) # The list has been appended Harshith.marks.append(89) print(Harshith.average()) print(Harshith.go_to_school()) print(Harshith.schools()) Messi = Student("Messi", "Barcelona") print(Messi.go_to_school()) Harshith.schoolname() # if it is a class method, an object can call the method or a class Student.schoolname()
#Name: Oluwatimi Owoturo #Student Number: 8606957 #Assignment 3 def runLength_Encode(f1,output): file1L = f1.read() f1.close() same = 0 letter = 0 sameL = [] previous = [] counter2=0 keepT = 1 keepT2 = 1 Encoded = '' for i in range(len(file1L)-1): if file1L[i] == file1L[i+1]: keepT2 = 1 if keepT != 1: keepT = 1 #Keeping track of spaces same = same+1 #sameL.append(same) #sameL.append(file1L[i]) if file1L[i] != file1L[i+1]: if keepT == 1: same = same+1 sameL.append(str(same)) #Appending the number of elements that are the same(determined by the counter) sameL.append(file1L[i-1]) #Appending previous to list. same = 0 keepT = keepT - 1 if keepT2 == 0: counter2 = counter2 + 1 sameL.append(str(counter2)) sameL.append(file1L[i]) counter2 = 0 if keepT2 == 1: keepT2 = keepT2 - 1 print("Encoding in progress......") import string j = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' k = j + '\t' + '\r\x0b\x0c' for i in range(len(k)): if (k[i] in sameL): #Checking for unsupported characters print("Unsupported characters") print("Restarting program") return main() #Restarting program main() else: for v in range(len(sameL)): Encoded = Encoded + sameL[v] #Adding elements of list to a string Encoded print("Encoding completed! ") compression = len(file1L) / len(Encoded) #Calculating compression ratio print("Compression ratio: " + str(compression)) output.write(Encoded) #Outputting to file output.close() def decode(file,output): file1L = file.read() file.close() h = [] decoded = "" num = "" j = 0 for i in range(len(file1L)-1): if file1L[i].isdigit() and file1L[i+1].isalpha() or file1L[i+1].isspace(): #Checking if element is a digit, alphabet or a space h.append(int(file1L[i])*file1L[i+1]) #Only happens if a one digit number elif file1L[i].isdigit() and file1L[i+1].isdigit(): h.append(int(file1L[i] + file1L[i+1])*file1L[i+2]) #Happens if a 2 digit number print("Decoding in progress.............") j = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' k = j + '\t' + '\r\x0b\x0c' for i in range(len(k)): if (k[i] in h): #Checking for unsupported characters print("Wrong encoded format") print("Restarting program") return main() print("Decoding completed") for i in range(len(h)): decoded = decoded + h[i] #Adding elements of list to a string decoded output.write(decoded) #Outputting the decode to a file output.close() def menu(userSelect): try: #Checking for user selection and input. #Also checking if file exists by using try and except if userSelect == "1": file = input("Input Source File Name: ").strip() file1 = open(file,'r') outfile = input("Input Destination File Name: ").strip() fileo = open(outfile,'w') runLength_Encode(file1,fileo) if userSelect == "2": file = input("Input Source File Name: ").strip() file1 = open(file,'r') outfile = input("Input Destination File Name: ").strip() fileo = open(outfile,'w') decode(file1,fileo) if userSelect == "3": quit except FileNotFoundError: print("Input file not found") return main() def main(): #Main program(Program handler) and menu print("Make your selection(Type 1,2 or 3): ") print("1. Encode a File") print("2. Decode a File") print("3. Exit") userSelect = (input("Your selection: ")).strip() menu(userSelect) #main main()
# Update using PDF from Euler Website 28 September # This works with larger numbers as well! # Two importan steps: # 1. sum of all numbers divisible by x or y is equal to # ( sum of all numbers divisible by x + # sum of all numbers divisible by x ) - # sum of all numbers divisible by x * y # 2. The sum of all multiples of x can be rewritten from # - [x, 2x, 3x, 4x, ...] to # - x * [1,2,3,4... floor(target / x) ] import math target = 999 def sum_divisible_by(n): p = math.floor(target / n) # step 2 return n * ((p * (p + 1)) / 2) print(sum_divisible_by(3) + sum_divisible_by(5) - sum_divisible_by(15)) # step 1
""" Read file into texts and calls. It's ok if you don't understand how to read files """ from collections import defaultdict import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) result = defaultdict(int) #iterate through calls list #create dictionary object with cell phone number as key and duration as value for callingnumber,callednumber, timestamp, duration in calls: result[callingnumber] += int(duration) result[callednumber] += int(duration) #print(result) #get the key containg max value phone_number=max(result, key=lambda k: result[k]) #join the phone numbers from each calls and text list to form a new list of list #calls_list =[ [x[0] , x[-1]] for x in calls] #combine list of list into a single list #print(calls_list) #calls_list_sorted=sorted(calls_list, key = lambda x: int(x[1])) #print(calls_list_sorted) print("{0} spent the longest time, {1} seconds, on the phone during September 2016.".format(phone_number, result[phone_number]))
import re import requests def get_text(): print("Please provide a word or sentence") return input() def parse_text(text): regex = re.compile("[^a-zA-Z]+") parsed = regex.sub("", text).lower() if not parsed: print("Your text is invalid") exit(-1) return parsed def is_palindrome(text): return text == text[::-1] def fetch_anagrams(text): url = f"http://anagramica.com/all/:{text}" try: data = requests.get(url).json() return data["all"] except: print(f"Cannot fetch anagrams, request error") exit() def main(): text = get_text() text = parse_text(text) print(f"Your text after parsing: {text}") print(f"Reversed: {text[::-1]}") if is_palindrome(text): print("Your text is a palindrome") else: print("Your text is not a palindrome") results = fetch_anagrams(text) print("\nAnagrams:") for result in results: print(result) if __name__ == "__main__": main()
import sys import logging logging.basicConfig(level=logging.DEBUG) def calculator(operation, number1, number2): result = '' if int(operation) == 1: result = float(number1) + float(number2) elif int(operation) == 2: result = float(number1) - float(number2) elif int(operation) == 3: result = float(number1) * float(number2) elif int(operation) == 4: result = float(number1) / float(number2) return result if __name__ == "__main__": operation = input("Podaj działanie, posługując się odpowiednią liczbą: 1 Dodawanie, 2 Odejmowanie, 3 Mnożenie, 4 Dzielenie: ") if int(operation) not in [1, 2, 3, 4]: logging.debug("Niepoprawny kod działania") exit(1) number1 = input("Podaj pierwszą wartość liczbową działania: ") number2 = input("Podaj drugą wartość liczbową działania: ") if int(operation) == 1: logging.debug("Dodaję %s i %s" % (number1, number2)) elif int(operation) == 2: logging.debug("Odejmuję %s i %s" % (number1, number2)) elif int(operation) == 3: logging.debug("Mnożę %s i %s" % (number1, number2)) elif int(operation) == 4: logging.debug("Dzielę %s i %s" % (number1, number2)) result = calculator(operation, number1, number2) logging.debug("Wynik to %.2f" % result) calculator(operation, number1, number2)
#PyPoll Python Challenge # Dependencies import os import csv # Set the Input datafile path DataFile = os.path.join("election_data.csv") # Variable Lists to store data total_votes = 0 candidate = "" candidate_votes = {} votes_percentage = {} winner_vote_count = 0 winner = "" # Gets data file with open(DataFile,'r', newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # Skips header row next(csvreader) # For every row in the input data file checks for votes for row in csvreader: # Total number of votes total_votes = total_votes + 1 # List of candidates with vote count candidate = row[2] if candidate in candidate_votes: candidate_votes[candidate] = candidate_votes[candidate] + 1 else: candidate_votes[candidate] = 1 # Calculates percentage and total number of votes for each winner candidate for person, vote_count in candidate_votes.items(): votes_percentage[person] = '{0:.3%}'.format(vote_count / total_votes) # Finds the winner of the election with popular votes if vote_count > winner_vote_count: winner_vote_count = vote_count winner = person # Prints the election analysis to the terminal print("Election Results") print ("--------------------------\n") print(f"Total Votes: {total_votes}") print ("\n--------------------------\n") for person, vote_count in candidate_votes.items(): print(f"{person}: {votes_percentage[person]} ({vote_count})") print ("\n--------------------------\n") print(f"Winner: {winner}") print ("\n--------------------------") # Exports results into text file output_file = os.path.join("election_data_output.csv") dashline = "-------------------------" with open(output_file,'w') as text: text.write ("Election Results\n") text.write(dashline + "\n") text.write(f"Total Votes: {total_votes}" + "\n") text.write(dashline + "\n") for person, vote_count in candidate_votes.items(): text.write(f"{person}: {votes_percentage[person]} ({vote_count})" + "\n") text.write(dashline + "\n") text.write(f"Winner: {winner}" + "\n") text.write(dashline + "\n")
import pygame.font class Scoreboard: """ A class to report scoring information on the top of the screen """ def __init__(self, screen, constants, stats): self.screen = screen self.screen_rect = screen.get_rect() self.constants = constants self.stats = stats # Font settings for scoring information self.text_color = (255, 255, 255) self.font = pygame.font.SysFont(None, 24) # Prepare the initial score images self.prep_score() self.prep_time() self.prep_level() self.prep_coins() self.prep_lives() def show_score(self): """ Draw scoreboard to the screen""" # score self.screen.blit(self.score_text, self.score_text_rect) self.screen.blit(self.score_image, self.score_rect) # Time self.screen.blit(self.time_text, self.time_text_rect) self.screen.blit(self.time, self.time_rect) # World self.screen.blit(self.world_text, self.world_text_rect) self.screen.blit(self.level, self.level_rect) # Coins self.screen.blit(self.coins_text, self.coins_text_rect) self.screen.blit(self.coins, self.coins_rect) # Lives self.screen.blit(self.lives_text, self.lives_text_rect) self.screen.blit(self.lives_image, self.lives_rect) def prep_score(self): """ Turn the score into a rendered image """ rounded_score = int(round(self.stats.score, -1)) score_str = "{:,}".format(rounded_score) self.score_text = self.font.render("SCORE", True, self.text_color, self.constants.bg_color) self.score_image = self.font.render(score_str, True, self.text_color, self.constants.bg_color) # Position the score at the top left of the screen self.score_text_rect = self.score_text.get_rect() self.score_rect = self.score_image.get_rect() self.score_text_rect.left = 20 self.score_text_rect.top = 10 self.score_rect.center = self.score_text_rect.center self.score_rect.top = self.score_text_rect.bottom def prep_time(self): """ Turn the time into a rendered image """ self.time_text = self.font.render("TIME", True, self.text_color, self.constants.bg_color) self.time = self.font.render(str(self.stats.time_left), True, self.text_color, self.constants.bg_color) # Position time between score and world self.time_text_rect = self.time_text.get_rect() self.time_rect = self.time.get_rect() self.time_text_rect.left = self.score_text_rect.right + 170 self.time_text_rect.top = 10 self.time_rect.center = self.time_text_rect.center self.time_rect.top = self.time_text_rect.bottom def prep_level(self): """ Turn the level into a rendered image """ self.world_text = self.font.render("WORLD", True, self.text_color, self.constants.bg_color) self.level = self.font.render(str(self.stats.level), True, self.text_color, self.constants.bg_color) # Position World Level at center of screen self.world_text_rect = self.world_text.get_rect() self.level_rect = self.level.get_rect() self.world_text_rect.center = self.screen_rect.center self.level_rect.center = self.world_text_rect.center self.world_text_rect.top = 10 self.level_rect.top = self.world_text_rect.bottom def prep_coins(self): """ Turn the coins into rendered image """ self.coins_text = self.font.render("COINS", True, self.text_color, self.constants.bg_color) self.coins = self.font.render(str(self.stats.coins), True, self.text_color, self.constants.bg_color) # Position coins between world and lives # Position time between score and world self.coins_text_rect = self.coins_text.get_rect() self.coins_rect = self.coins.get_rect() self.coins_text_rect.left = self.world_text_rect.right + 170 self.coins_text_rect.top = 10 self.coins_rect.center = self.coins_text_rect.center self.coins_rect.top = self.coins_text_rect.bottom def prep_lives(self): """ Show how many lives are left """ self.lives_text = self.font.render("LIVES", True, self.text_color, self.constants.bg_color) self.lives_image = self.font.render(str(self.stats.lives_left), True, self.text_color, self.constants.bg_color) # Position lives at the top right of the screen self.lives_text_rect = self.lives_text.get_rect() self.lives_rect = self.lives_image.get_rect() self.lives_text_rect.right = self.screen_rect.right - 20 self.lives_rect.center = self.lives_text_rect.center self.lives_text_rect. top = 10 self.lives_rect.top = self.lives_text_rect.bottom
from typing import List class Solution: @classmethod def two_sum(cls, nums: List[int], target: int) -> List[int]: for i, n1 in enumerate(nums): for j, n2 in enumerate(nums): if i >= j: continue if (nums[i] + nums[j]) == target: return [i, i+1] return [] class Test: def __init__(self, *, nums=None, target=None, expects=None): self.__nums = nums self.__target = target self.__expects = expects @property def nums(self): return self.__nums @property def target(self): return self.__target @property def expects(self): return self.__expects if __name__ == '__main__': test_cases = [ Test(nums=[2, 7, 11, 15], target=9, expects=[0, 1]), Test(nums=[2, 7, 11, 15], target=0, expects=[]), Test(nums=[2, 7, 11, 15], target=18, expects=[1, 2]), ] for case in test_cases: ans = Solution.two_sum(case.nums, case.target) assert ans == case.expects
year = int(input("What year is it? ")) if year % 100 == 0 and year % 400 == 0: print("It's a leap year. February has 29 days this year.") else: print("It's not a leap year. February has 28 days this year.")
mass = float(input("What's the object's mass? ")) weight = mass * 9.8 if weight > 500: print("The object is too heavy.") if weight < 100: print("The object is too light.")
def main(): name = input("What's the name of the file? ") file = open(name, 'r') for x in range(5): line = file.readline() if line: print(line) main()
kms = int(input("How many kilometers? ")) miles = kms * 0.6214 print("That's", format(miles, '.2f'), "miles")
def main(): def calculate_fat(): fat = int(input("How many grams of fat do you eat per day? ")) fat_calories = fat * 9 print("That's ", fat_calories, " calories", sep="") def calculate_carbs(): carbs = int(input("How many carbs do you eat per day? ")) carb_calories = carbs * 4 print("That's ", carb_calories, " calories", sep="") calculate_fat() calculate_carbs() main()
tuition = 8000 multiplier = 1 print("Year \tTuition") for x in range(1, 6): multiplier += 0.03 tuition *= multiplier print(x, " \t$", format(tuition, '.2f'), sep="")
def main(): try: file = open('numbers.txt', 'r') total = 0 line = file.readline() lines = 0 while line != "": try: number = int(line) total += number lines += 1 except ValueError: print("There was an error in converting the string", line, "to an integer.") line = file.readline() average = total/lines print("The average of the integers in the file is", average) file.close() except IOError: print("There was an error in opening and reading data from the file.") main()
a = int(input("How many Class A tickets were sold? ")) b = int(input("How many Class B tickets were sold? ")) c = int(input("How many Class C tickets were sold? ")) total = (a*20) + (b*15) + (c*10) print("$", total, " was generated through ticket sales", sep="")
def main(): numbers = [] for x in range(20): number = int(input("Enter a number: ")) numbers.append(number) lowest = min(numbers) highest = max(numbers) total = 0 for y in numbers: total += y average = total / 20 print("The lowest number is", lowest) print("The highest number is", highest) print("The total is", total) print("The average is", format(average, '.2f')) main()
def main(): name = input("Enter your name: ") blurb = input("Describe yourself: ") file = open("html.txt", "w") file.write("<html>\n") file.write("<head>\n") file.write("</head>\n") file.write("<body>\n") file.write(" <center>\n") file.write(" <h1>" + name + "</h1>\n") file.write(" </center>\n") file.write(" <hr />\n") file.write(" " + blurb + "\n") file.write(" <hr />\n") file.write("</body>\n") file.write("</html>") main()
number = int(input("Enter a number 1 through 7: ")) if number < 1 or number > 7: print("That's outside of the valid range") else: if number == 1: print("Monday") if number == 2: print("Tuesday") if number == 3: print("Wednesday") if number == 4: print("Thursday") if number == 5: print("Friday") if number == 6: print("Saturday") if number == 7: print("Sunday")
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6 """ from utils.ListNode import ListNode,List2LN,LN2List,LN2String # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def merge2Lists(self, phead, qhead): """ 合并2个有序链表 """ head = ListNode(0) p = head while phead and qhead: if phead.val < qhead.val: p.next = phead phead = phead.next else: p.next = qhead qhead = qhead.next p = p.next if phead: p.next = phead if qhead: p.next = qhead return head.next def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if not lists: return [] from functools import reduce res = reduce(self.merge2Lists, lists) # res = self.merge2Lists(lists[0],lists[1]) return res lists = [ [3,4,5], [1,3,4], [2,6], [3,4,8], [0,5,7] ] lists = [List2LN(x) for x in lists] s = Solution() res = s.mergeKLists(lists) print(LN2List(res)) print(LN2String(res))
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。 如果二叉树的两个节点深度相同,但父节点不同,则它们是一对堂兄弟节点。 我们给出了具有唯一值的二叉树的根节点 root,以及树中两个不同节点的值 x 和 y。 只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true。否则,返回 false。 示例 1: 输入:root = [1,2,3,4], x = 4, y = 3 输出:false 示例 2: 输入:root = [1,2,3,null,4,null,5], x = 5, y = 4 输出:true 示例 3: 输入:root = [1,2,3,null,4], x = 2, y = 3 输出:false 提示: 二叉树的节点数介于 2 到 100 之间。 每个节点的值都是唯一的、范围为 1 到 100 的整数。 """ # 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 isCousins(self, root, x, y): """ :type root: TreeNode :type x: int :type y: int :rtype: bool """ parent = {} depth = {} def dfs(node,par=None): if node: depth[node.val] = 1 + depth[par.val] if par else 0 parent[node.val] = par dfs(node.left,node) dfs(node.right,node) dfs(root) return depth[x] == depth[y] and parent[x] != parent[y]
# -*- coding:utf-8 -*- """ 给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。 示例 : 输入: [1,2,1,3,2,5] 输出: [3,5] 注意: 结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。 你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现? 解题思路: 假设两个数只出现一次的数为 a, b 1. 第一次异或遍历求出 x = a ^ b 2. 找出 x 的最低位的1 (x & -x), 记这个数为y, 可以按这位上为1和0 (y & 1), 将数组可以分为 2 堆, a 和 b就分别是这两堆数中唯一一个出现只出现一次的数字 3. 再次遍历数组, 便可以分离出 a 和 b """ from typing import List class Solution: def singleNumber(self, nums: List[int]) -> List[int]: x = 0 for num in nums: x ^= num y = x & -x a, b = 0, 0 for num in nums: if num & y: a ^= num else: b ^= num return [a, b] s = Solution() nums = [1, 2, 1, 3, 2, 5] print(s.singleNumber(nums))
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素。 示例 1: 输入: [1,3,5,6], 5 输出: 2 示例 2: 输入: [1,3,5,6], 2 输出: 1 示例 3: 输入: [1,3,5,6], 7 输出: 4 """ def searchInsert(nums,target): L = 0 R = len(nums) - 1 while L<=R: mid = (L + R) // 2 # print(mid) if nums[mid] == target: return mid elif nums[mid] < target: L = mid+1 else: R = mid-1 return L nums,target = [1,3,5,6], 7 print(searchInsert(nums,target))
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给你一个由 '('、')' 和小写字母组成的字符串 s。 你需要从字符串中删除最少数目的 '(' 或者 ')' (可以删除任意位置的括号),使得剩下的「括号字符串」有效。 请返回任意一个合法字符串。 有效「括号字符串」应当符合以下 任意一条 要求: 空字符串或只包含小写字母的字符串 可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」 可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」 示例 1: 输入:s = "lee(t(c)o)de)" 输出:"lee(t(c)o)de" 解释:"lee(t(co)de)" , "lee(t(c)ode)" 也是一个可行答案。 示例 2: 输入:s = "a)b(c)d" 输出:"ab(c)d" 示例 3: 输入:s = "))((" 输出:"" 解释:空字符串也是有效的 示例 4: 输入:s = "(a(b(c)d)" 输出:"a(b(c)d)" 提示: 1 <= s.length <= 10^5 s[i] 可能是 '('、')' 或英文小写字母 """ class Solution: def minRemoveToMakeValid(self, s: str) -> str: stack = [] n = len(s) r = [] new_s = "" for i in range(n): if s[i] == '(': stack.append(i) elif s[i] == ')': if stack: stack.pop() else: r.append(i) for i in range(n): if not i in stack + r: new_s += s[i] return new_s
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。 说明:不要使用任何内置的库函数,如 sqrt。 示例 1: 输入:16 输出:True 示例 2: 输入:14 输出:False """ class Solution: def isPerfectSquare(self, num: int) -> bool: """ 牛顿迭代法: 牛顿逼近法本来就是求方程近似解的,只要这道题目本来就是f(x)=x*x - num = 0,有整数解。 那不断逼近整数解的Xn = Xm - f(Xm) / f'(Xm)。如果能得到这个Xn就可以返回True了。 f'(X)是f(X)的导数,为2x,因此Xn=(Xm - num / Xm) / 2 持续迭代下去就好了。 :param num: :return: """ r = num while r*r > num: r = (r+num/r)/2 print(r) if r*r == num: return True return False def isPerfectSquare3(self, num: int) -> bool: """ 二分区间 :param num: :return: """ if num == 0: return False # 高低指针 left, right = 0, num while left <= right: mid = left+(right-left)//2 tmp = mid*mid if tmp == num: return True elif tmp>num: # mid的平方比num大 说明是sqrt(num)在左区间 right = mid - 1 else: # mid的平方比num小 说明sqrt(num)在右区间 left = mid + 1 return False def isPerfectSquare2(self, num: int) -> bool: """ 1+3+5+7+9+…+(2n-1)=n^2 完全平方数肯定是前n个连续奇数的和 :type num: int :rtype: bool """ sum = 1 while num>0: num -= sum sum += 2 return num ==0 s = Solution() print(s.isPerfectSquare3(9999999999999999**2))
# -*- coding:utf-8 -*- """ 给你两个 没有重复元素 的数组nums1 和nums2,其中nums1是nums2的子集。 请你找出 nums1中每个元素在nums2中的下一个比其大的值。 nums1中数字x的下一个更大元素是指x在nums2中对应位置的右边的第一个比x大的元素。如果不存在,对应位置输出 -1 。 示例 1: 输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. 输出: [-1,3,-1] 解释: 对于 num1 中的数字 4 ,你无法在第二个数组中找到下一个更大的数字,因此输出 -1 。 对于 num1 中的数字 1 ,第二个数组中数字1右边的下一个较大数字是 3 。 对于 num1 中的数字 2 ,第二个数组中没有下一个更大的数字,因此输出 -1 。 示例 2: 输入: nums1 = [2,4], nums2 = [1,2,3,4]. 输出: [3,-1] 解释: 对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。 对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。 提示: 1 <= nums1.length <= nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 104 nums1和nums2中所有整数 互不相同 nums1 中的所有整数同样出现在 nums2 中 进阶:你可以设计一个时间复杂度为 O(nums1.length + nums2.length) 的解决方案吗? """ from typing import List class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: """ 单调栈 + 哈希表 :param nums1: :param nums2: :return: """ stk = [] ht = {} for i in range(len(nums2) - 1, -1, -1): ht[nums2[i]] = i while stk and nums2[stk[-1]] <= nums2[i]: stk.pop() ht[nums2[i]] = nums2[stk[-1]] if stk else -1 stk.append(i) res = [ht[x] for x in nums1] return res nums1 = [2, 4] nums2 = [1, 2, 3, 4] s = Solution() print(s.nextGreaterElement(nums1, nums2))
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。 字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。 示例 1: 输入:text = "nlaebolko" 输出:1 示例 2: 输入:text = "loonbalxballpoon" 输出:2 示例 3: 输入:text = "leetcode" 输出:0 提示: 1 <= text.length <= 10^4 text 全部由小写英文字母组成 """ class Solution(object): def maxNumberOfBalloons(self, text): """ :type text: str :rtype: int """ balon = [0, 0, 0, 0, 0] for i in text: if i == 'b': balon[0] += 1 if i == 'a': balon[1] += 1 if i == 'l': balon[2] += 1 if i == 'o': balon[3] += 1 if i == 'n': balon[4] += 1 balon[3] //= 2 balon[2] //= 2 return min(balon)
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给定一个正整数,返回它在 Excel 表中相对应的列名称。 例如, 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... 示例 1: 输入: 1 输出: "A" """ def convertToTitle(n): key_list = [x for x in range(1, 27)] value_list = [chr(ord('A') + x) for x in range(0, 26)] dic = dict(zip(key_list, value_list)) # 键值对字典 ans = '' # 辗转相除 while n != 0: n, b = divmod(n, 26) if b == 0: b = 26 n -= 1 ans = dic[b] + ans # print(n,b,ans) return ans if __name__ == '__main__': print(convertToTitle(888))
# -*- coding:utf-8 -*- """ 给你一个非递减的 有序 整数数组,已知这个数组中恰好有一个整数,它的出现次数超过数组元素总数的 25%。 请你找到并返回这个整数 示例: 输入:arr = [1,2,2,6,6,6,6,7,10] 输出:6 提示: 1 <= arr.length <= 10^4 0 <= arr[i] <= 10^5 """ from typing import List import collections class Solution: def findSpecialInteger(self, arr: List[int]) -> int: c = collections.Counter(arr) return c.most_common(1)[0][0] s = Solution() print(s.findSpecialInteger([1, 2, 2, 6, 6, 6, 6, 7, 10]))
# -*- coding:utf-8 -*- """ 给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。 如果存在多个数字二进制中 1 的数目相同,则必须将它们按照数值大小升序排列。 请你返回排序后的数组。 示例 1: 输入:arr = [0,1,2,3,4,5,6,7,8] 输出:[0,1,2,4,8,3,5,6,7] 解释:[0] 是唯一一个有 0 个 1 的数。 [1,2,4,8] 都有 1 个 1 。 [3,5,6] 有 2 个 1 。 [7] 有 3 个 1 。 按照 1 的个数排序得到的结果数组为 [0,1,2,4,8,3,5,6,7] 示例 2: 输入:arr = [1024,512,256,128,64,32,16,8,4,2,1] 输出:[1,2,4,8,16,32,64,128,256,512,1024] 解释:数组中所有整数二进制下都只有 1 个 1 ,所以你需要按照数值大小将它们排序。 示例 3: 输入:arr = [10000,10000] 输出:[10000,10000] 示例 4: 输入:arr = [2,3,5,7,11,13,17,19] 输出:[2,3,5,17,7,11,13,19] 示例 5: 输入:arr = [10,100,1000,10000] 输出:[10,100,10000,1000]   提示: 1 <= arr.length <= 500 0 <= arr[i] <= 10^4 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def count_1(self, n): res = 0 while (n): n &= n - 1 res += 1 return res def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: (self.count_1(x), x))
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5] 示例 1: 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 输出: 6 解释: 节点 2 和节点 8 的最近公共祖先是 6。 示例 2: 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 输出: 2 解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': # p、q 的值均大于节点的值,则在节点右子树中寻找公共祖先 if(root.val<p.val and root.val<q.val): return self.lowestCommonAncestor(root.right,p,q) # p、q 的值均小于节点的值,则在节点左子树中寻找公共祖先 if(root.val>p.val and root.val>q.val): return self.lowestCommonAncestor(root.left,p,q) # p、q 其一大于或等于root,其一在 root 小于或等于root,此时 root为其公共祖先 return root
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给定一个二叉树,原地将它展开为链表。 例如,给定二叉树 1 / \ 2 5 / \ \ 3 4 6 将其展开为: 1 \ 2 \ 3 \ 4 \ 5 \ 6 """ from utils.TreeNode import TreeNode, List2TN, TN2List class Solution: def flatten(self, root: TreeNode) -> None: """ 前序遍历 :param root: :return: """ stack = [root] while stack and root: cur = stack.pop() if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) if cur != root: root.left, root.right = None, TreeNode(cur.val) root = root.right def flatten2(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ stack = [root] res = [] while stack and root: cur = stack.pop() if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) res.append(cur.val) if res: while res: root.left = None root.right = TreeNode(res.pop(0)) root = root.right root = List2TN([1, 2, 5, 3, 4, None, 6]) s = Solution() s.flatten(root) print(TN2List(root))
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 你可以假设数组是非空的,并且给定的数组总是存在众数。 示例 1: 输入: [3,2,3] 输出: 3 示例 2: 输入: [2,2,1,1,1,2,2] 输出: 2 """ class Solution: def majorityElement(self, nums): nums.sort() return nums[len(nums)//2] def majorityElement2(self, nums): """ 摩尔投票算法 :param nums: :return: """ cnt, ret = 0, 0 for num in nums: if cnt == 0: ret = num if num != ret: cnt -= 1 else: cnt += 1 return ret so = Solution() nums = [2,2,1,1,1,2,2] print(so.majorityElement(nums))
# -*- coding:utf-8 -*- """ 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。 示例: 输入:nums = [1,2,3,4] 输出:[1,3,2,4] 注:[3,1,2,4] 也是正确的答案之一。 提示: 1 <= nums.length <= 50000 1 <= nums[i] <= 10000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List class Solution: def exchange(self, nums: List[int]) -> List[int]: """ 双指针, i 指向左边第一个偶数 j 指向右边第一个奇数 :param nums: :return: """ i, j = 0, len(nums) - 1 while (i < j): if (i < j and nums[i] & 1 == 1): i += 1 if (i < j and nums[j] & 1 == 0): j -= 1 nums[i], nums[j] = nums[j], nums[i] return nums
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。 传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。 返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。 示例 1: 输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5 输出:15 解释: 船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示: 第 1 天:1, 2, 3, 4, 5 第 2 天:6, 7 第 3 天:8 第 4 天:9 第 5 天:10 请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。 示例 2: 输入:weights = [3,2,2,4,1,4], D = 3 输出:6 解释: 船舶最低载重 6 就能够在 3 天内送达所有包裹,如下所示: 第 1 天:3, 2 第 2 天:2, 4 第 3 天:1, 4 示例 3: 输入:weights = [1,2,3,1,1], D = 4 输出:3 解释: 第 1 天:1 第 2 天:2 第 3 天:3 第 4 天:1, 1 """ class Solution(object): def shipWithinDays(self, weights, D): """ 二分查找法 答案一定是在max(weights) 和 sum(weights) 中间的 因为左端点对应每天一条船,右端点对应只有一条超级大船。 利用二分法,每一次循环模拟运货的过程,然后根据需要的天数与 输入 D 的关系来调整区间左右端点。 :type weights: List[int] :type D: int :rtype: int """ left = max(weights) right = sum(weights) while left<right: # 船的最大运输能力 mid = (left+right)//2 # ----以下为模拟运货过程---- tmp = 0 day = 1 for weight in weights: tmp += weight # 装的货比船运输能力多 需要加一艘船运输 if tmp > mid: day += 1 tmp = weight # print(left,mid,right,day,D) # 所花时间比给定时间多 需要加大船的运输量 在右区间 if day > D: left = mid + 1 # 所花时间比给定时间少或相同 尽量在左区间找到更少的 if day <= D: right = mid return left weights = [3,2,2,4,1,4] D = 3 s = Solution() print(s.shipWithinDays(weights,D))
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给出数字 N,返回由若干 "0" 和 "1"组成的字符串,该字符串为 N 的负二进制(base -2)表示。 除非字符串就是 "0",否则返回的字符串中不能含有前导零。 示例 1: 输入:2 输出:"110" 解释:(-2) ^ 2 + (-2) ^ 1 = 2 示例 2: 输入:3 输出:"111" 解释:(-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3 示例 3: 输入:4 输出:"100" 解释:(-2) ^ 2 = 4 for each number, we first consider its binary mode, then we check 10,1000,100000,... one by one for example, 6 = '110', so for the second '1', in base -2, it makes the initial number decrease 4(+2 -> -2) so we jusr make the initial number add 4, then 6 -> 10 = '1010', later we consider the first '1', it makes the initial number decrease 16(+8 -> -8), then we add 16, 10 -> 26 = '11010', now we get the answer. https://leetcode.com/problems/convert-to-base-2/discuss/265507/JavaC%2B%2BPython-2-lines-Exactly-Same-as-Base-2 https://leetcode.com/problems/convert-to-base-2/discuss/265688/4-line-python-clear-solution-with-explanation """ class Solution(object): def baseNeg2(self, N): """ 1 = 1 2 = 4-2 = 110 3 = 4-2+1 = 111 :type N: int :rtype: str """ neg = [1 << i for i in range(1, 33, 2)] for mask in neg: if N & mask: N += mask*2 return bin(N)[2:] N = 255 s = Solution() print(s.baseNeg2(N))
# -*- coding:utf-8 -*- """ 链接:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst 给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。 示例: 输入: 1 \ 3 / 2 输出: 1 解释: 最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。 提示: 树中至少有 2 个节点。 本题与 783 https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/ 相同 """ from utils.TreeNode import TreeNode class Solution: def inorder(self, root): if not root: return [] return self.inorder(root.left) + [root.val] + self.inorder(root.right) def getMinimumDifference(self, root: TreeNode) -> int: nums = self.inorder(root) return min(nums[i] - nums[i - 1] for i in range(1, len(nums)))
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给你一个正整数的数组 A(其中的元素不一定完全不同), 请你返回可在 一次交换(交换两数字 A[i] 和 A[j] 的位置)后得到的、按字典序排列小于 A 的最大可能排列。 如果无法这么操作,就请返回原数组。 示例 1: 输入:[3,2,1] 输出:[3,1,2] 解释: 交换 2 和 1 示例 2: 输入:[1,1,5] 输出:[1,1,5] 解释: 这已经是最小排列 示例 3: 输入:[1,9,4,6,7] 输出:[1,7,4,6,9] 解释: 交换 9 和 7 示例 4: 输入:[3,1,1,3] 输出:[1,1,3,3] 提示: 1 <= A.length <= 10000 1 <= A[i] <= 10000 [1,6,9,4,6,7] 1 6 7 4 6 9 1 2 5 3 2 4 -> 1 2 5 2 3 4 5 4 3 2 1 -> 5 4 3 1 2 最后一个比它右边的值大的数字就是左边需要交换的数字 使用单调栈存储正常排列的数字索引 """ class Solution(object): def prevPermOpt1(self, A): """ 只能进行一次交换 交换后的构成的数组的元素字典序要小于A :type A: List[int] :rtype: List[int] """ n = len(A) stack = [] L = -1 for i in range(n): while stack and A[stack[-1]] > A[i]: L = max(L, stack.pop()) stack.append(i) if L == -1: return A while A[stack[-1]] >= A[L]: stack.pop() R = stack[-1] A[L], A[R] = A[R], A[L] return A # B = sorted(A) # if B == A: # return A # 下面代码有错 [3,2,1] -> [3,1,2] # i = 0 # while A[i] == B[i]: # i += 1 # t, k = A[i + 1], i + 1 # 存储需要交换的值和索引 # for j in range(i + 2, n): # if A[j] < A[i] and A[j] > t: # t,k = A[j],j # A[i], A[k] = A[k], A[i] # return A s = Solution() A = [3, 1, 1, 3] print(s.prevPermOpt1(A))