text
stringlengths
37
1.41M
weight = raw_input("How much do you weight?: ") try: weight = int(weight) #if the input entered was an integer it will continue or... except: print "Invalid entry." quit() moonWeight = weight/6.0 print moonWeight
import sqlite3 # items.dbに接続 connectdb = sqlite3.connect('items.sqlite3') cdbcursor = connectdb.cursor() # テーブルの作成 cdbcursor.execute("create table items(id,name)") # データの挿入 cdbcursor.execute("insert into items values(1,'あいてむ')") cdbcursor.execute("insert into items values(2,'アイテム')") cdbcursor.execute("insert into i...
input1 = input("Please enter the sentence") print("The original sentence is : ",input1) print("The modified sentence is : ", input1.replace("python", "pythons"))
in1 = input("Enter the string ") # Defining function to be called def string_alternative(in1): out = "" # Checking for even index and copy data only for even index's for i in range(len(in1)): if i%2 == 0: out = out + in1[i] # printing the input and processed output print("input ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.metrics import mean_squared_error train = pd.read_csv('winequality-red.csv') #Checking for Null values print("before processing, null count is : " , sum(train.isnull().sum() != 0)) # handling null or mi...
from collections import defaultdict import math import sys fileName = input("Enter file name : ") source = input("Enter Origin_city: ") destination = input("Enter Destination_city: ") def Graph(): dictionary = defaultdict(list) with open(fileName, 'r') as file: for line in file: ...
import abc from abc import abstractmethod import random from insertData import InsertData class Employee(): def __init__(self, name, address, salary): self.name = name self.address = address self.salary = salary self.codOnly = None self.paymentMethod = None self.bel...
''' Simple Linear Regression About this Notebook In this notebook, we learn how to use scikit-learn to implement simple linear regression. We download a dataset that is related to fuel consumption and Carbon dioxide emission of cars. Then, we split our data into training and test sets,create a model using training set...
# Spiral Matrix # Given aNXN matrix, starting from the upper right corner of the matrix start printingvalues in a # counter-clockwise fashion. # E.g.: Consider N = 4 # Matrix= {a, b, c, d, # e, f, g, h, # i, j, k, l, . visit 1point3acres.com for more. # m, n, o, p} # Your function s...
# possible password # dfs problem # Given an input N that tells you also how many digits are in the password, print all possible passwords import string import pdb def possblePassword(N): result = list() path = list() abc = list(string.ascii_lowercase) dfs(0,N,result,path,abc,0) print result print len(result) #...
class person: def __init__(x, name, age): x.name = name x.age = age person1 = person("Muhammad Ali",25) print(person1.name) print(person1.age)
def two_complement(value : int, nb_bits : int): """Return the two's complement of value with nb_bits bits""" assert -(2**(nb_bits-1)) <= value < 2**(nb_bits-1), "Value "+str(value) + " should have been between " + str(-2**(nb_bits-1)) + " and " + str(2**(nb_bits-1)-1) return ("{0:{fill}" + str(nb_bits) + ...
def code_cesar(code): alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" index = alphabet.index(code) encodage = {} for i, x in enumerate(alphabet): #print(i,x) encodage[x] = alphabet[(i + index) % len(alphabet)] return encodage def code_cesar_reverse(code): alphabet = "ABCDEFGHIJKLMNO...
for value in range(1,21): if value == 4 or value == 13: print(f"{value} is unlucky") elif value%2==0: print (f"{value} is even") else: print(f"{value} is odd")
# Create a list called instructors instructors = [] # Add the following strings to the instructors list # "Colt" # "Blue" # "Lisa" instructors.extend(["Colt", "Blue", "Lisa"]) print(instructors) # Remove the last value in the list instructors.pop() print(instructors) # Remove the first value in the list ins...
#!/usr/bin/python """Computes the reverse compliment of a DNA sequence""" import sys import string argc = len(sys.argv) toCompliment = string.maketrans("ACGT", "TGCA") test = True test_file_loc = "test_data" usage = """revc.py [data file] Computes the reverse compliment of the given DNA sequence in 'data file'""" if...
#this programme generate a set of decision trees for Hangman according to all the English words # I have used Python tree class implemented by Joowani https://github.com/joowani/binarytree import pickle from binarytree import tree, bst, convert, heap, Node, pprint print 'Start reading the dictionary file...' with ope...
print("-" * 30 + " Begin Section 6 开场" + "-" * 30) print("这是Python的第六次课程,主要讲数据的预处理") print("1. 数据类型转换 \n2. 索引设置") print("-" * 30 + "End Section 0 开场" + "-" * 30) print("\n") import pandas as pd # Section 1 数据类型转换 df = pd.read_excel(r"/Users/yons/Desktop/py_help/04_lesson.xlsx", sheet_name="Sheet3") df1 = df # python ...
#Variable five = 5 six = 6 print(five* six) #String Variable person_one = 'I said the number: ' person_two = 'I have different number: ' print(person_one,five) print(person_two,six) print('Sum of their Number: ', five*six) print(print(5)) #will print None ## creating custom Method def print_something(): print('W...
def your_friends(): friend = input('Type your friends name separated by comma: \n') friend_list = friend.split(',') friend_without_space= [] for f in friend_list: friend_without_space.append(f.strip()) return friend_without_space def your_best_friend(): best_friend = input('Type your B...
def insertion_sort(*args): # check type of the args (because type of args is tuple and it is immutable) if type(args) is tuple: array = list(args) else: array = args for i in range(2, len(array)): # hold to compare with others hold = array[i] # divide l...
from random import randint def partition(array: list, p: int, r: int) -> int: x = array[r] i = p-1 for j in range(p, r): if array[j] <= x: i += 1 array[i], array[j] = array[j], array[i] array[i+1], array[r] = array[r], array[i+1] return i+1 def ra...
""" Example script for connecting to the database. - For an SQLite database, specifying a new filename will create a database - For a MySQL database, connecting to an existing database will also create any tables that are missing from the database schema. """ import os import datetime import numpy as np impo...
class Player: def __init__(self, intitalRow, initialColumn): # Instance variables that contain the player's position in the maze. self.rowPosition = intitalRow self.columnPosition = initialColumn # This method moves the player up. # The player's row position is decremented by one. ...
# Original code found: https://www.reddit.com/r/learnprogramming/comments/4w1duu/how_can_i_loop_through_every_pixel_in_an_image/ # Code was altered for project # from PIL import Image import cv2 # Imports OpenCV for image manipulation import os # Imports the os class to use for directory navigation from PIL im...
# a = matrix, b = matrix, c = row_1, d = row_2 def swapRows(a, b, c, d): n = len(a) for i in range(n): a[c][i], a[d][i] = a[d][i], a[c][i] b[c], b[d] = b[d], b[c] # i = column index def notNullColumns(a, b, i): j = 0 if a[i][i] == 0: while a[i][i] == 0 and j < len(a): if...
import numpy as np #MLP with 2-3 hidden layers from scratch def process_data(data,mean=None,std=None): # normalize the data to have zero mean and unit variance (add 1e-15 to std to avoid divide-by-zero) if mean is not None: # mean and std is precomputed with the training data data = (data - mea...
# percorrer listas nomes = [ "jose", "talita", "aline santos", "jessica", "sabrina", "juliana", "julia", "sasha", ] print("Listar todos os elementos:") for nome in nomes: # caso a condição seja satisfeita, é pulado para a próxima iteração com o 'continue' if nome.startswith("S")...
# Importando Matplotlib e Numpy import matplotlib.pyplot as plt import numpy as np from sklearn import datasets import pandas as pd from sklearn.model_selection import train_test_split, cross_val_score # Importando o módulo de Regressão Linear do scikit-learn from sklearn.linear_model import LinearRegression def pre...
""" Em python um módulo é lido como se fosse um script. Deste modo, sempre que um módulo for importado será executado como um script. Por isso tomar cuidado ao importar módulos. Se o objetivo for criar um módulo que funcione como um script, sendo executando diretamente, pode ser necessário utilizar __name__ == "__main...
# This program scrapes the Wikipedia page listing Armenian Artists for a list of their full names. import urllib3 import certifi from bs4 import BeautifulSoup http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) wiki="https://en.wikipedia.org/wiki/List_of_Armenian_artists" # Open the URL. ...
list3 = 'listen' list4 = 'silent' def find_string_anagram(list3, list4): if(sorted(list3) == sorted(list4)): return 'string is anagram' else: return 'string is not anagrams' print(find_string_anagram(list3, list4))
#!/usr/local/bin/python3 a = 'jitendra Ramdas More' def reverse(a): str = "" for i in a: str = i + str return str print(reverse(a)) s = 'jitendra Ramdas More' def reverser(s): if len(s) == 0: return s else: return reverser(s[1:]) + s[0] print(reverser(a)) string = ['b', 'c', 'd', 'e', 'f',...
def is_starts_or_ends_with(str,substr): if str[0] == substr: print(substr, ' is a Prefix') elif str[-1] == substr: print(substr, 'is a Suffix') else: print(substr, ' is neigher Prefix not Suffix') a = ['h4ow','h8i', 'a23re','rajes34singh', 'yo76u'] substring = ['h', 'i', 'e', 'r', 'o'] for (inputlis...
#!/usr/local/bin/python3 a = [10, 30, 20, 40, 50, 60, 70] b = [10, 30, 40, 60, 80] t = (10, 20, 30, 40, 50) ts = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'xyz') # the use of tuple() function # when parameter is not passed tuple1 = tuple() print(tuple1) # when an iterable(e.g., list) is passed tup...
p1=int(input()) p2=int(input()) p3=int(input()) p4=int(input()) p5=int(input()) p6=int(input()) if(p1==p3): if(p3==p5): print ("yes") else: print("no") else: if(p2==p4): if(p4==p6): print ("yes") else: print ("no") else: print("no")
# coding: utf-8 # ## python 编程中一些常用的小技巧 # # In[1]: # 1. 原地交换两个数 x,y = 3, 5 print(x,y) x,y = y,x print(x,y) # In[2]: # 2. 序列数据的倒置 test_list = [1,2,3] print(test_list) test_list.reverse() print(test_list) test2_list = test_list[::-1] print(test2_list) test_str = "Hello world" test2_str = test_str[::-1] print(test...
from LinkedList import LinkedList from Stack import Stack # 1. Use your linked list code and add a method called reverse() that will reverse the linked list. You can start with making a reversed copy and build up to reversing the linked list "in place" as a strecth goal. For example if your linked list is 3->5->6 your ...
class Engine: def start(self, starting_speed): if starting_speed < 3000: return False else: return True class Battery: def __init__(self): self.power = 0 def charge(self, charging_power): if charging_power < 1000: return False e...
#!/usr/bin/python import __future__ import sys import getch from PyDictionary import PyDictionary try: # for Python2 from Tkinter import * except ImportError: # for Python3 from tkinter import * try: # python 2 from tkFont import Font except ImportError: # python 3 from tkinter.font import Font ''' Cod...
print('==== Desafio 35 ====') #Desenvolva um programa que leia o comprimento de três retas e # diga ao usuário se elas podem ou não formar um triângulo. print('-=-'*20) print('Analisador de Triângulos') print('-=-'*20) a = float(input('Insira o 1º comprimento: ')) b = float(input('Insira o 2º compriment...
# Faça um programa que leia o peso de cinco pessoas. No final, # mostre qual foi o maior e o menor peso lidos. ''' lista = [] for i in range(1, 6): peso = float(input(f'Peso da {i}º pessoa: ')) lista.append(peso) print(f'O MAIOR peso foi: {sorted(lista, reverse=True)[0]}') print(f'O MENOR peso foi: {...
print('==== Desafio 8 ====') #Escreva um programa que leia um valor em metros e o #exiba convertido em centímetros e milímetros. mt = float(input('Digite a metragem:: ')) to_dm = mt * 10 #decímetros to_cem = mt * 100 #centímetros to_mm = mt * 1000 #melímetros to_dam = mt / 10 #Decâmetros to_hm = mt / 100 #Hequi...
# Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma mensagem: # - O primeiro valor é maior # - O segundo valor é maior # - Não existe valor maior, os dois são iguais a = float(input('Digite o primeiro número: ')) b = float(input('Digite o segundo número: ')) if a > b: ...
print('==== Desafio 11 ====') #Faça um programa que leia a largura e a altura de uma #parede em metros. Calcule a sua área e a quantidade de #tinta necessária para pintá-la, sabendo que cada litro #de tinta pinta uma área de 2m(2). larg = float(input('Digite a largura da parede: ')) alt = float(input('Digite a ...
print('==== Desafio 9 ====\n') #Faça um programa que leia um número inteiro #qualquer e moestre na tela a sua tabuada. num = int(input('Digite um número para ver a sua tabuada:: ')) print('-'*12) print('{} x 1 = {}\n{} x 2 = {}\n{} x 3 = {}\n'.format(num, 1 * num, num, 2 * num, num, 3 * num)) print('-'*12)
#!/usr/bin/env python """ checkTicket.py check current ticket list for winner """ from playLotto import * import sys def main(ticket,draw,game=PowerBall['parts']): "play the game, get your score" val=0 cost,playresdict=getWinners(ticket,draw) for tkt in playresdict.keys(): if playresdict[tkt]['value']>...
""" Programme principal du pendu """ #Import du module random pour pouvoir selectionner un mot au hasard dans les listes import random #Import des variables from variables import * #Import des fonctions from fonctions import * #Tant que le joueur ne quitte pas le jeu while quitter != "o" and "O": ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 5 22:36:10 2019 @author: cannybiscuit """ def bubble_sort_algorithm(array): n = len(array) # Loop through the entire array for i in range(n): # Here we repeatedly step through the list comparing adjacent pairs ...
from helpers import find_manhattan_distance file = open("input.txt", "r") lines = file.readlines() # parse coordinates to tuples # (x, y, count_locations, is_outside) coordinates = [ (int(line.split(",")[0]), int(line.split(",")[1]), 0, False) for line in lines] # find min/max coordinates min_x = coordinat...
orignal = [[[1],2],3,4,[5,[6,7]],8] def flatten(nested): try: for sublist in nested: for element in flatten(sublist): yield element except TypeError: yield nested print list(flatten(orignal))
#Write a Python program that takes mylist = [1, 2, 3, 4, 5] and print sum of all the items in the list. mylist=[1, 2, 3, 4, 5] x=sum(mylist) print(x)
#Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and sort the list using list sort function. mylist=["WA","CA","NY","IL","WA","CA","WA"] mylist.sort() print(mylist)
#Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and print how many times each state appeared in the list. mylist=["WA", "CA", "NY","IL","WA","CA","WA"] x=mylist.count("WA") y=mylist.count("CA") print("WA appeared :",x,"times") print("CA appeared :",y,"times")
# Write Python program that asks for first name and last name seprately, then print the full name FirstName = input("First Name:") LastName = input("Last Name:") print(FirstName,LastName)
from decimal import Decimal from collections.abc import Callable from typing import Union Number = Union[float, Decimal] def newton_method( f: Callable[[Number], Number], f_: Callable[[Number], Number], x0: Number, count: int = 20, ) -> Number: ''' Newton's Method f : target function ...
def func(): for i in range(0, 5): try: return i finally: if i != 3: # SyntaxError: 'continue' not supported inside 'finally' clause continue print(func())
def solve(array): mid = calc(array) return (array[:mid+1], array[mid:]) def calc(array): high = len(array) low = 0 while low < high: mid = (low + high)//2 if mid == 0: return 0 elif mid == len(array) - 1: return len(array) - 1 a, b, c = arra...
def nthprime(n: int) -> int: ''' Returns nth prime number. Reference: https://stackoverflow.com/a/48040385/13977061 ''' start = 2 count = 0 while True: if all([start % i for i in range(2, int(start**0.5 + 1))]): count += 1 if count == n: ...
import numpy as np from position import Position EMPTY_SPACE = '.' class OutOfBoundsException(Exception): pass class Board: BOARD_SIZE = 15 def __init__(self, ): self.spaces = np.zeros((self.BOARD_SIZE, self.BOARD_SIZE), 'string') # TODO: find a better way to initialize to spaces for x in range(le...
"""======================================================================================================================== Calvin is driving his favorite vehicle on the 101 freeway. He notices that the check engine light of his vehicle is on, and he wants to service it immediately to avoid any risks. Luckily, a servi...
#!/usr/bin/python import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("-f",help="Interpret a brainfuck file") args = parser.parse_args() open_file = args.f def get_symbols(file_name): with open(file_name , 'r') as file: return [char for char in file.read() if char != '\n...
# 2019 카카오 개발자 겨울 인턴십 : 크레인 인형뽑기 게임 def solution(board, moves): answer = 0 pre_dolls = [''] line_dict = {idx: 0 for idx in range(1, len(board)+1)} for mov in moves: which_line = line_dict[mov] if which_line > len(board) - 1: continue mov -= 1 while board[whi...
def alpha_reverse(list): f_output=input("Enter the file name with extension name(.txt) in which the decrypted code will be saved: ") coding=list[0]+list[1]+list[2]+list[3] a_list=list[5:] dlist=[] if coding=='#a1#': for i in a_list: if ord(i)>=97 and ord(i)<=122: ...
month = input("Enter the name of the month: ") days_in_month = 31 if month == "April" or month == "June" or month == "September" or month == "November": days_in_month = 30 elif month == "February": days_in_month = "28 or 29" print(month, "has", days_in_month, "days in it.")
import pandas data = pandas.read_csv("nato_phonetic_alphabet.csv") # code = data["code"].tolist() # letter = data["letter"].tolist() # nato_alpha = {letter[i]: code[i] for i in range(len(letter))} # same thing as above but shorter nato_alpha = {row.letter: row.code for (index, row) in data.iterrows()} on = True whi...
#!/usr/bin/env python3 # James Jessen # CptS 434 - Assignment 1 # Due 2019-09-05 # Python Tutorial: https://docs.python.org/3.7/tutorial/index.html # Python Documentation: https://docs.python.org/3.7/index.html # python 1hw/hw1.py > 1hw/output.txt from LinearRegression import linearRegression as linReg dataPa...
print('''This is a car game. It can be played like this--- first You have to start the game by typing 'start' and then the journey will be started. If you want to stop the car, then just type "park".Finally if you want to quit, then just type "q" to stop the game. ''') while True: a=input("") if a=="start":...
''' Created on Mar 7, 2018 @author: awon ''' # dynamic variable's declaration # define functions using "def" key word # No need to define return value to function' # Indentation is very important # ":" is written after a conditional or loop statement def add(a,b): return a+b def add_fixed_value(a): y=5 ...
cars = 100 #The variable for total cars in existence. space_in_a_car = 4 #The variable for amount of people-space per car. drivers = 30 #The amount of total drivers assigned to a car. passengers = 90 #The amount of total passengers available to occupy car space. cars_not_driven = cars - drivers #The remainder of cars r...
from random import randrange failNum = 4 skill = 4 def dieMaker(sides): """return a die roller function""" def die(): return randrange(1, sides+1) return die def roll(numDice, die): """ Run game mechanic roll. Roll a number of dice then check to see if any are below the suceess...
# #author: Grace Hsu #Date: 12/5/18 Edits # import os import csv import datetime bank_path = os.path.join('Resources', 'budget_data.csv') #create a file for the financial summary financial_analysis_summary = open('financial_analysis.txt', 'w').close() financial_output_path = os.path.join('financial_analysis.txt') ...
for i in range(1,100) : msg = '' if i%3 == 0 : msg = 'Fizz' if i%5 == 0 : msg += 'Buzz' if not msg : print (i) else : print(msg)
''' Timer.py Written using Python 2.7.12 @ Matt Golub, August 2018. Please direct correspondence to mgolub@stanford.edu. ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import time class Timer(object): '''Class for profiling computa...
/* Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. /* class Solution(object): def sortedSquares(self, A): """ :type A: List[int] :rtype: List[int] """ squares = [] for num...
#!/usr/bin/env python # coding: utf-8 # # Assessment 1: I can train and deploy a neural network # At this point, you've worked through a full deep learning workflow. You've loaded a dataset, trained a model, and deployed your model into a simple application. Validate your learning by attempting to replicate that work...
import urllib from urllib . request import urlopen import ssl ssl._create_default_https_context = ssl._create_unverified_context def is_connected(site): try: urlopen(site,timeout=1) return True except urllib.error.URLError as Error: print(Error) return False urlSite= input(...
from random import randint T = int(raw_input()) Smax = int(raw_input()) print(T) def randomString(): string ="" for i in range(Smax): string += str(randint(0,3)) return string for i in range(T): print(str(Smax) + " "+randomString()+"1")
formatter = "{} {} {} {}" # Replaces each of the individiual values below with each {} above. # So 1 will replace the first {} and so on print(formatter.format(1,2,3,4)) print(formatter.format("one", "two", "three", "four")) print(formatter.format(True, False, False, True)) #For each formatter value below it adds {} ...
#!/usr/bin python # Program to multiply two matrices using nested loops import random import numpy as np def matrixMaker(N,M): X = np.random.random((N,M)) return X def main(): N = 250 X = matrixMaker(N,N) Y = matrixMaker(N,N+1) result = np.matmul(X, Y) # result is Nx(N+1) # result = ...
#!/bin/env python # input section name = input('Please enter your name: ') # output section print ( "hello ", name, ". Nice to meet you." ) # Ask a couple of questions and assoc the result to a dictionary res = {'more_csc': (input("Are you interested in pursuing CSC beyond this class? "))} # The developer has writt...
#from abc import ABC import abc class Employee(abc.ABC): def __init__(self, name, cpf, pay): self._name = str(name) self._cpf = str(cpf) self._pay = float(pay) @abc.abstractmethod def get_bonus(self): return self._pay * 0.10 class Manager(Employee): def __init__(se...
import argparse import logging import sys log = open('assignment10.log', 'a') sys.stdout = log logging.basicConfig(filename='assignment10.log',level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('--integer', action='store', dest='integer', type=int, help='this is the number we will find the s...
# coding=UTF-8 # 415. 字符串相加 类似于链表相加 # 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。 # 注意: # num1 和num2 的长度都小于 5100. # num1 和num2 都只包含数字 0-9. # num1 和num2 都不包含任何前导零。 # 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。 ''' 我的思路: 1、先将字符串都倒序,因为从个位数开始加起 2、用0在末尾填充,保证两个字符串长度一致 3、增加一个变量add,表示进位多少;res用来拼接结果 4、%取余数得到当前位的数字,//得到进位数字。 5、不能...
# coding=UTF-8 # 二维数组中的查找 # 题目描述: # 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。 # 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 """ 从左上角开始入手之所以不可行的原因,是因为以左上角为基准遍历时,满足条件的数字可能分布在两侧,所以并不能很好的缩小搜索范围。 以左下角或右上角为锚点开始查找,满足条件的数字值只可能分布在一侧,可以缩小搜索范围。 从某种角度看,这种解法类似于“二分法”,只不过不是严格意义上均匀的二分。 """ class Solution(object): def...
# coding=UTF-8 # 二叉树的最大深度 """ 1. 迭代法:从上到下按层级遍历二叉树,有多少层即二叉树有多深(即为求二叉树的深度) 2. 递归法:比较每一条路径的长短 """ class BiNode: def __init__(self, val): self.left = None self.right = None self.val = val class BiTree: def __init__(self): self.root = None # 添加节点 """ 判断根结点是否存在,如果不存在则插入根结点...
######################################### 反转链表 ######################################### # coding=UTF-8 class ListNode: def __init__(self, x): self.val = x self.next = None # 迭代思想 def ReverseList(self, pHead): if pHead == None or pHead.next == None: return pHead cur = pHead ...
# coding=UTF-8 # 二叉树的最小深度 """ 1. 迭代法: 算法遍历二叉树每一层,一旦发现某层的某个结点无子树,就返回该层的深度,这个深度就是该二叉树的最小深度 2. 递归法: 用递归解决该题和"二叉树的最大深度"略有不同。      主要区别在于对“结点只存在一棵子树”这种情况的处理,在这种情况下最小深度存在的路径肯定包括该棵子树上的结点 """ class BiNode: def __init__(self, val): self.left = None self.right = None self.val = val class BiTree:...
# coding=UTF-8 # 53. 最大子序和 # 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 """ 解题思路: 1. 如果当前和大于0,则加上下一个数(当前和是正的 对后面的求和“有益处”) 2. 如果当前和小于或等于0,则将下一个数赋给当前和 3. 最后比较当前和与存储最大值的变量 取最大值 """ class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ ...
# coding=UTF-8 # 4. 寻找两个有序数组的中位数 # 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 # 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。 class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ nums1.exte...
# 28.实现strStr() # 给定一个 haystack 字符串和一个 needle 字符串 # 在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。 class Solution: def strStr(self, haystack, needle): if needle not in haystack: return -1 return haystack.find(needle) # 切片法 def strStr(self, haystack, needle): l ...
# 347. 前K个高频元素 # 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 # 输入: nums = [1,1,1,2,2,3], k = 2 # 输出: [1,2] """ 1. 建立哈希表(字典)存储数字及其出现的次数 2. 根据字典的值逆序排序 3. 拿出前K个元素的key """ class Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ ...
#def even_numbers(function): #def wrap(numbers): #print(function()) #if numbers % 2 == 0: # return wrap def even_numbers(function): def wrap(numbers): result = list(filter(lambda x: x % 2 == 0, numbers)) return function(result) return wrap @even_...
lst = [] num = int(input("Number of inputs:")) for n in range (num): Ascii_val = ord(input()) lst.append(Ascii_val) print("The sum is :" ,sum(lst))
import random heads = 1 tails = 0 valid_guesses = [heads, tails] correct_statement = "Correct! The coin flip landed " incorrect_statement = "incorrect! The coin flip landed " guess_list = [] coin_flip_otcme = random.randint(0,1) for guess in valid_guesses: def coin_flip(user_guess): if coin_flip_otcme == us...
input_string = input("Enter a list element separated by space ") list = input_string.split() print("print in reverse order") print(list[::-1])
def num(X,N,n): #print(pow(n,N)) if(pow(n,N)<X): return num(X,N,n+1)+num(X-pow(n,N),N,n+1) elif(pow(n,N)==X): return 1; else: return 0; x=int(input("enter the value of X = ")) y = int(input("enter the value of N = ")) #print(type(x),type(y)) print(num(x,y,1))
def takefirst(elem): return elem[0] # the first line of input is the number of rows of the array n = int(input()) a = [] for i in range(n): a.append([(j) for j in input().split()]) b=[] for i in range(int(n/2)): a[i][1] = '-' a.sort(key=takefirst) #print(a) for j in range (n): b.append(a[j][1]) pri...
input_string = input("Enter a list of strings separated by space = ") a = input_string.split() x = input("Enter a list of queries separated by space = ") b = x.split() n=len(b) c=[] for i in range(n): c.append(a.count(b[i])) print("Resultant array = ",c)
import time import itertools from collections import OrderedDict def information(element, item): if item in element: element[item] = element[item] + 1 else: element[item] = 0 element = OrderedDict(sorted(element.items(), key=lambda x: x[1], reverse=True)) return element def...