text
stringlengths
5
121k
def factorial(n): if n == 0: return 1 try: return factorial(n-1) * n except RecursionError: raise ValueError def reverse(text): if len(text) == 0: return text else: return reverse(text[1:]) + text[0] def bunny(count): if count...
numbers = [4,5,3,6,5,] x_bar = sum(numbers)/len(numbers) print("MEAN : ", x_bar, "\n") variance = 0 print(str("x").ljust(4), "|", str("x_xbar").ljust(6), "|", str("x_xbar_squared").ljust(8), "|") print(str("-"*4).ljust(4), "+", str("-"*6).ljust(6), "+", str("-"*14).ljust(8), "-") for number in num...
x = 20 def greet(name, gender): if gender == "male": print(f"Hello Mr {name}..!") else: print(f"Hello Mrs {name}..!") greet("Bolu", "female") people = [("bolu", "male", 23), ("ade", "female", 15), ("sholu", "female", 45), ("manny", "male", 33)]...
my_range = range(23) my_range_list = list(range(23)) my_range_list = list(range(10,23)) my_range_list = list(range(2,23,3)) my_ages = [2,8,1,1,0,4,2,7,5,99,5] ...
def multiplyStrings(s1, s2): isneg1, isneg2 = 1 if s1[0]=='-' else 0, 1 if s2[0]=='-' else 0 s1, s2 = s1[1:] if isneg1 else s1, s2[1:] if isneg2 else s2 finalsign = "-" if isneg1+isneg2 == 1 else "" ans = [0]*(len(s1)+len(s2)) id1, id2 = 0, 0 for i in s1[::-1]: i = ord(i)-48 ...
def rotateby90(a, n): for i in range((n+1)//2): for j in range(n//2): a[i][j], a[n-i-1][n-j-1], a[n-j-1][i], a[j][n-i-1] = \ a[j][n-i-1], a[n-j-1][i], a[i][j], a[n-i-1][n-j-1] """ from the rotation pattern it is observed that the rotation of each element can be visualised as a...
def reverse_alt_k(head, k): ar = [] cur = head while cur: ar.append(cur.val) cur = cur.next br = [] for i in range(0, len(ar), k): cur = ar[i:i+k] cur.reverse() for j in cur: br.append(j) newll = linked_list() for i in br: newl...
import math a = input() b = input() ponto1 = a.split(' ') ponto2 = b.split(' ') ponto1[0], ponto1[1] = float(ponto1[0]), float(ponto1[1]) ponto2[0], ponto2[1] = float(ponto2[0]), float(ponto2[1]) difX = ponto1[0]-ponto2[0] difY = ponto1[1]-ponto2[1] distancia = math.sqrt(math.pow(difX, 2) + math.pow(difY, 2)) print('...
""" anagram_runner.py This program uses a module "anagram.py" with a boolean function areAnagrams(word1, word2) and times how long it takes that function to correctly identify two words as anagrams. A series of tests with increasingly long anagrams are performed, with the word length and time to identify outpu...
""" Created on Wed Nov 8 12:10:34 2017 @author: paulyang """ def countingSort(nums): assert min(nums) >= 0, 'Numbers in nums must be nonnegative.' k = max(nums) aux = [0] * (k + 1) res = [0] * (len(nums) + 1) for num in nums: aux[num] += 1 for i ...
import tello billy = tello.Tello() station = [[2, "cw", 90, "forward", 100], [3, "ccw", 90, "forward", 80], [4, "ccw", 90, "forward", 40], [5, "ccw", 90, "forward", 40], [6, "cw", 90, "forward", 60], [1, "ccw", 90, "forward", 40]] destination = 2 billy.send("command", 3) billy.send("battery?", 3) ...
"""Network base class""" import os import pickle from abc import ABC, abstractmethod """In Pytorch you would usually define the `forward` function which performs all the interesting computations""" class Network(ABC): """ Abstract Dataset Base Class All subclasses must define forward() method """ ...
n1=0O17 n2=0B1110010 n3=0X1c2 n=int(n1) print("octal 17 is:",n) n=int(n2) print("Binery 1110010 is:",n) n=int(n3) print("HexaDecimal 1c2 is:",n) """ int float complex bool str bytes bytearray list tuple dict range set Mapping """
class disJointItem(): def __init__(self,label): self.parent = self self.rank = 0 self.label = label def FindRoot(self): if self.parent != self : self.parent = self.parent.FindRoot() return self.parent ''' if self.parent == self : return self else : return Find(self.parent)...
from numpy import * kFloatType = float64 def arrayf( arg ): return array( arg, kFloatType ) def asarrayf( arg ): return asarray( arg, kFloatType ) def zerosf( arg ): return zeros( arg, kFloatType ) def identityf( arg ): return identity( arg, kFloatType ) def emptyf( arg ): return empty( a...
from math import fabs n = int(input("Enter a grid size (3 or 4)")) pole = [[] for i in range(n)] pole_win = [[] for k in range(n)] if n == 3: pole_numb = 9 empty_value = [2, 2] else: pole_numb = 16 empty_value = [3, 3] def init(): active_line = 0 for k in reversed(range(1, pole...
import random def print_graph(G_adj_list): for i in range(len(G_adj_list)): for j in range(len(G_adj_list[0])): print(format(G_adj_list[i][j],'2d'),end=' ') print() def print_graph_to_file(G_adj_list): with open('sample_graph.txt', 'w') as fp: for i in range(len(G_adj_list)): fp.write(' '.join(list(map...
''' https://oj.leetcode.com/problems/min-stack/ Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in th...
def prime_checker(number): for i in range(2, number): if number % i == 0: return "not prime" else: return "prime" num = int(input("Enter number: ")) print(prime_checker(number=num))
import fileinput import random from classes import WordController, User def main(): ''' Main function. Responsible for program's work. ''' file_name = make_userfile() fl = open(file_name, "a") user = User(file_name) iterat = True while iterat == True: print(menu()) secti...
class Choice(object): def __init__(self, desc=None): self.desc = desc def validate(self, choice): pass class YesNoChoice(Choice): def __init__(self, desc=None): super(DiscreteChoice, self).__init__(desc) class DiscreteChoice(Choice): def __init__(self, options, desc=None): ...
Backslash = "\\" decompressed_string ="" print() while True: string_entered=input ("\nEnter a string to decompress (example 'to be or not to(13,3)' \ will be decompressed to 'TO BE OR NOT TO BE' see more examples in the pdf attached \ or press 'enter' to quit: ") #Quit the program if the...
l1 = [1,5,4,8] l2 = [8,4,5,9,8] l3 = [8,8,7,5,4] s1 = sum(l1) s2 = sum(l2) s3 = sum(l3) print(s1,s2,s3) s1, s2, s3 = sum(l1), sum(l2), sum(l3) print(s1,s2,s3) s1, s2, s3 = map(sum,(l1,l2,l3)) print(s1,s2,s3)
from random import randint random_number = randint(1, 10) user_numer = input("Podaj liczbe od 1 do 10") tries = 1 while int(user_numer) != random_number: tries += 1 user_numer = input('Sporóbuj jeszcze raz!') print('KONIEC po {} próbach'.format(tries))
import csv from advanced_python_regex import Faculty f = Faculty('faculty.csv') emails = f.get_emails() with open ('emails.csv', 'wb') as csv_file: email_writer = csv.writer(csv_file, delimiter='\n') email_writer.writerows([emails])
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self,data): newNode = Node(data) if self.head == None: self.head = newNode return ...
from copy import deepcopy from fractions import Fraction from utils import to_fraction class Vector(list): def __init__(self, arg=None): """ Creates a new Vector from the argument Usage: >> Vector(), Vector(None) Vector([]) creates empty vector >> Vector([5, 6, 6.7, Fracti...
import turtle from random import randrange from freegames import square,vector food=vector(0,0) snake =[vector(10,0)] aim = vector(0,-10) def change(x,y): aim.x =x aim.y = y def inside(head): return-200<head.x<190 and -200<head.y,190 def move(): head = snake[-1].copy() head.move(aim...
def sumarAcumulado(lista): lis=[] for k in range (1,len(lista)+1): lis.append(sum(lista[:k])) return lis def recortarLista(lista): list=[] for k in range(1,len(lista)-1): list.append(lista[k]) return list def estanOrdenados (lista): var=True for k in...
from tkinter import * from typing import List root = Tk() root.title("CodeBasic") root.geometry("640x480") listbox = Listbox(root, selectmode="extended", height=0) listbox.insert(0, "사과") listbox.insert(1, "딸기") listbox.insert(2, "바나나") listbox.insert(END, "수박") listbox.insert(END, "포도") listbox.pack() ...
from time import sleep from org.jointheleague.ecolban.rpirobot import SimpleIRobot, Sonar robot = SimpleIRobot() sonar = Sonar() def move_forward(): """Move the robot forward approximately one square""" robot.driveDirect(500, 500) sleep(1.642) robot.stop() def move_forward_to_wall(): "...
def calculate_kg_to_lbs(kg): answer = (kg) * (2.2) print(answer) print('Enter your weight in kilograms') kg = int(input()) print('Your weight in pounds is: ') calculate_kg_to_lbs(kg)
print('What is the current temperature of the chicken?') def checkTemp(Temp): if Temp > 260: return 'It is probably cooked' elif Temp < 260: return 'More heat more time' Temp = int(input()) Result = checkTemp(Temp) print(Result)
print('What is your first name strangerrr?') firstname = str(input()) print('What is your last name?') lastname = str(input()) print('Type a number from 0 to 6 and press ENTER') def funnyjobs(number): if number == 0: return 'the Cowboy' elif number == 1: return 'the Stripper' eli...
import collections import sys directions = { 'E': (1, 0), 'N': (0, 1), 'W': (-1, 0), 'S': (0, -1) } stack = [] with open(sys.argv[1]) as f: for regex in f: regex = regex.strip() current = (0, 0) stack = [] valid_moves = collections.default...
import sys class HelloWorldGenerator(): """Wooo a docstring""" def __init__(self): print("HelloWorld") self.str = "Hello World" def sayHello(self,string:'wow_an_annotation'): print(self.str) def main(): hwg = HelloWorldGenerator() hwg.sayHello() if __name__ == '__main__': main()
import tkinter as tk import tkinter.font as font root = tk.Tk() HEIGHT = 400 WIDTH = 300 def createAccount(): topCreate = tk.Toplevel(height = HEIGHT, width = WIDTH) topCreate.title("Register") def storeData(): Users = open('Users.txt', 'a') username = user_login_entry.get() ...
''' Created on 2018年2月23日 @author: Administrator ''' class Adder(): def __init__(self, start = []): self.data = start def add(self, y): print('Not Implemented') def __add__(self, other): return self.add(self.data, other) class ListAdder(Adder): def add(...
""" author: Mitchell Hornsby file: Label.py purpose: Provides an object that displays text on a Pygame surface. """ import pygame as pg class Label(object): def __init__(self, text, position, font, fontColor=(0,0,0), bgColor=(255,255,255), padding=(10, 6), transparent=False, visible=True): """ text...
""" Created on Wed Jul 17 13:14:05 2019 @author: ahmedshaban """ count = 0 s = 'azcbobobegghakl' for letter in s: if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u': count += 1 print ("Number of vowels: " + str(count))
import FileIO.StockDriver as stockDriver def menu(): loop = False driver = None while not loop: print("==========================================================================") print("Welcome to the Stock Exchange!") print("============================================...
num1=float(input("Enter the first number")) num2=float(input("Enter the second number")) num3=input("input your operation") if num3=='+': print(num1+num2) if num3=='+': print(num1+num2) if num3=='-': print(num1-num2) if num3=='/': print(num1/num2) if num3=='*': print(num1*num2) if num3=='%': pri...
v=8 print("enter a number") v2=int(input()) if(v2>v): print("greater") else: print("smaller")
print("pattern printing") a=int(input("Enter how many rows you want:\n")) print("Enter 1 or 0") b=bool(input("1 for true and 0 for false:\n")) if b=="1": for i in range(0,a+1): print("*"*i) if b=="0": for i in range(a,0,-1): print("*"*i)
def avg(a,b): """This is doc type of a function in which we write for what we have made the function""" average=(a+b)/2 return average """ this is not doc type ,this is comment for multi line """ ''' this is also a multi line comment to check that single cote also works''' v=avg(...
n = int(input()) lista = [100, 50, 20, 10, 5, 2, 1] print('{}'.format(n)) for i in lista: notas = n // i n = n % i print('{} nota(s) de R$ {},00'.format(notas, i))
cod1 = int(input()) pecas1 = int(input()) valor1 = float(input()) cod2 = int(input()) pecas2 = int(input()) valor2 = float(input()) total = pecas1 * valor1 + pecas2 * valor2 print('VALOR A PAGAR: R$ {}'.format(round(total, 2)))
def convert_file_to_list(file): with open(file, 'r', encoding='utf-8') as f: text_list = f.readlines() return text_list def write_to_sorted_file(): files = {'1.txt': convert_file_to_list('1.txt'), '2.txt': convert_file_to_list('2.txt'), '3.txt': convert_file_to_list('3.txt')} ...
""" 1) Understand - Functions - find_max_profit should receive a list of stock prices as an input, return the max profit that can be made from a single buy and sell. You must buy first before selling, no shorting - prices is an array of integers which represent stock prices and we need to find the max, the min, and...
import openpyxl import os from Loan import * from datetime import datetime def calculateDays(loan): today = datetime.today().strftime("%m/%d/%y") borDate = datetime.strftime(loan.dateBorrowed.value, "%m/%d/%y") a = datetime.strptime(borDate, "%m/%d/%y") b = datetime.strptime(today, "%m/%d/%y") ...
class Pupil: def __init__(self, name, surname): self.name = name self.surname = surname self.marks = {} @property def name(self): return self.__name @name.setter def name(self, name): if len(name) >= 3: self.__name = name else: ...
import random class Die: def __init__(self, sides): self._sides = sides self._value = None def roll(self): self._value = random.randint(1, self._sides) def get_sides(self): return self._sides def get_value(self): return self._value die_computer = Die(8); die_use...
import re import urlparse from bs4 import BeautifulSoup class HtmlParser(object): def _get_new_urls(self, page_url, soup): new_urls = set() links = soup.find_all('a', href = re.compile(r"/wiki/(\w)")) for link in links: new_url = link['href'] new_full_url =...
default_name = "you" def two_fer(name=default_name): if isinstance(name, str): name = name.strip() if name == "": name = default_name else: name = default_name return f"One for {name}, one for me."
from collections import defaultdict def beaut(input): index = defaultdict(list) for idx, char in enumerate(input): index[char].append(idx) found = [len(input)] for seek in map(chr, range(0x21, 0x7f)): if not index[seek]: continue r = [f for f in f...
""" Created on Mon Oct 02 12:52:45 2017 @author: rishi """ import sqlite3 import datetime conn=sqlite3.connect('GEDCOM_DATA.db') conn.text_factory = str def Story02(): query1="select NAME,BIRTHDAY,MARRIED from INDIVIDUAL AS I,FAMILY AS F where I.ID=F.HUSBAND_ID OR I.ID=F.WIFE_ID" result1=conn...
def checkio(number: int) -> str: if number % 15 == 0: number = "Fizz Buzz" elif number % 5 == 0: number = "Buzz" elif number % 3 == 0: number = "Fizz" else: pass return str(number) test = [15, 6, 5, 7] for i in range(len(test)): item = test[i] ...
"""returns the first word in a given text.""" def first_word(text: str) -> str: print(text) text = text.replace(",", " ").replace(".", " ") text = text.strip().split() return text[0] test = [ "Hello world", " a word ", "don't touch it", "greetings, friends", "... and s...
a= int(input("provide first number : ")) b= int(input("provide second number : ")) sign= input("the operation : ") def calc(a,b): if sign == '+': c= a+b elif sign== '-': c= a-b elif sign=='*': c= a*b elif sign=='/': c= a/b else: print("This option is not ...
name = "My Name is Sahil Nagpal and I love Programming" first2index = name[:2] last2index = name[len(name)-2:len(name)] print(first2index + last2index) print(name.replace('e','r',2))
A = int(input("Input A:")) B = int(input("Input B:")) if A < B: a = [] for i in range(A, B+1): a.append(1) print(a) if A > B: b = [] for k in range(B, A+1): b.append((A + 1) - k) print(b)
import manim class Example(manim.Scene): def construct(self): circle = manim.Circle() circle.set_fill(manim.PINK, opacity=0.5) anim = manim.Create(circle) self.play( anim ) ...
from tkinter import * def miles_to_km(): miles = float(miles_input.get()) km = miles * 1.689 km_result.config(text=f"{km}") window = Tk() window.title("Miles to km Converter") window.minsize(width=300, height=100) window.config(padx=20, pady=20) miles_input = Entry(width=7) miles_input.grid(column=1, r...
from human import Human from ai import AI def compare_gestures(gesture1, gesture2): if gesture1.name == gesture2.name: return "tie" elif gesture1.name == "Rock": if gesture2.can_beat_rock: return "lose" elif gesture1.name == "Paper": if gesture2.can_beat_paper: ...
""" Credit: https://www.thepythoncode.com/article/encrypt-decrypt-files-symmetric-python """ from cryptography.fernet import Fernet from encrypt_gen import * import time def encrypt(filename, key): """ Given a filename (str) and key (bytes), it encrypts the file and write it """ f = Fernet(key) wi...
def work(): while True: try: age = int(input("pls input your age: ")) except ValueError: print("sorry i did'nt understund that") continue else: if age < 18: print("you can not vote") elif age>18: prin...
from functools import reduce nums = [3, 2, 4, 6, 8, 9] evens = list(filter(lambda n:n%2==0, nums)) doubles = list(map(lambda n:n*2, evens)) sum = reduce(lambda a,b: a+b, doubles) print(evens) print(doubles) print(sum)
import time while True: try: print(" Press Enter to Start the Timer and CTRL-C to end the timer") start_time = time.time() print(" The timer is started") while True: print("time elapsed = ", round(time.time() - start_time, 0), 'secs', end='\n') time.sl...
a=[1,2,3,"12a","13s",12,"sd"] i=0 b=[] while i<len(a): if type(a[i])==type(i): b.append(a[i]) i=i+1 print(b)
import requests from bs4 import BeautifulSoup url="https://finance.yahoo.com/quote/GOOGL?p=GOOGL&.tsrc=fin-srch&guccounter=1" header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36'} html_...
word1 = "Good" word2 = "Morning" word3 = "to you too!" print(word1, word2) sentence = word1 + " " + word2 + " " + word3 print(sentence)
from tkinter import * abc = ['a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H','i','I','j','J','k','K', 'l','L','m','M','n','N','o','O','p','P','q','Q','r','R','s','S','t','T','u','U','v','V','w', 'W', 'x','X','y', 'Y','z', 'Z'] ciph = "Here will be the output" def caesar (): ...
def main(number): digits = [int(c) for c in number] matching_digits = [c for i, c in enumerate(digits[:-1]) if c == digits[i+1]] if digits[-1] == digits[0]: matching_digits.append(digits[-1]) return sum(matching_digits) if __name__ == '__main__': with open('data/input01.txt') as f: ...
from collections import defaultdict def get_next_xy(x, y, values): if x == 0 and y == 0: return 1, 0 elif values[(x - 1, y)] and not values[(x, y - 1)]: return x, y - 1 elif values[(x, y+1)] and not values[(x-1, y)]: return x-1, y elif values[(x+1, y)] and not values[(x, y+1)]:...
checker = False while checker == False: try: user_input = int(input("Please enter a number between 1-100: ")) except ValueError: print("The value entered was not a number") if user_input < 1: print("The number you entered is too low, Try again") elif user_input > 100: ...
from random import randint class Sequence: def __init__(self): self.number = [] self.last_number = None def random_sequence(self): self.number.append(randint(0, self.last_number))
import csv import sys from search import * Cities = {} Heuristics = {} Connections = {} def load_data(directory): """ Load data from CSV files into memory. """ with open(f"{directory}/cities.csv", encoding="utf-8") as f: reader = csv.DictReader(f,fieldnames=["City"]) index ...
def main(): number_list = [] number_sum = 0 for i in range(5): number_input = int(input("Enter a number: ")) number_list.append(number_input) number_sum += number_list[i] number_average = number_sum / 5 print("The first number is {}".format(number_list[0])) print("The las...
TARIFF_11 = 0.244618 TARIFF_31 = 0.136928 tariff_per_kwatt = int(input("Which tariff? 11 or 31: ")) daily_usage_kwatt = float(input("Enter daily use in kWh: ")) billing_days = int(input("Enter number of billing days: ")) if tariff_per_kwatt == 11: estimated_bill = TARIFF_11 * daily_usage_kwatt * billing_days pr...
def print_pyramid(num): """ >>> print_pyramid(5) o oo ooo oooo ooooo >>> print_pyramid(3) o oo ooo """ for num in range(num): line = 'o' for num in range(num): line += 'o' print(line)
from functools import reduce domain = [1, 2, 3, 4, 5] our_range = map(lambda num: num * 2, domain) print(list(our_range)) evens = filter(lambda num: num % 2 == 0, domain) print(list(evens)) the_sum = reduce(lambda acc, num: acc + num, domain, 0) print(the_sum) words = ['Boss', 'a', 'Alfred', 'fig', 'Daemon', 'dig...
from vehicle import Vehicle class Car(Vehicle): default_tire = 'tire' def __init__( self, engine, tires=None, distance_traveled=0, unit='kilometers', **kwargs ): super().__init__( distance_traveled=distance_traveled, unit=uni...
import argparse parser = argparse.ArgumentParser( description='contains: Search for words including partial word.' ) parser.add_argument( 'snippet', help='partial (or complete) string to search for in words' ) parser.add_argument( '--version', '-v', action='version', version='%(prog)s 1.0...
ages = { 'Keith': 30, 'Levi': 25, 'John': 20, } del ages['Keith'] print(ages) values = ['Kevin Bacon', 60, '555-555-5555', False] val = not values[-1] print(val) ages = { 'Keith': 30, 'Levi': 25, 'John': 20, } output = [str(value) for value in ages.values()] print(output) names = ['Alice', ...
ascii_number=65 for i in range(4): for j in range(i+1): character=chr(ascii_number) print(character, end=" ") ascii_number +=1 print()
list=(1,2,3,4,5,6,7) if 5 in list: print("yes") else: print("no")
for i in range(0,10): if i%2==0: print (i,"even number") else: print (i,"odd number")
'''given a integer number, print it last digit''' num=int(input("enter the number:")) rem=num%10 print(rem)
''' to print multipliacation table of a given number by using fuction''' def multi(a): product=1 for i in range(11): product=a*i print (f"{a}*{i}={product}") a=int(input("enter the nnumber")) multi(a)
'''find factorial num''' def fact(a): product=1 for i in range(2,a+1): product=product*i return product a=int(input("enter the number:")) c=fact(a) print(f"the ans is{c}")
'''have parameter and return type''' def dev(a,b): return a/b a=int(input("enter the num:")) b=int(input("enter the num:")) c=dev(a,b) print(f"the ans is {c}")
alphabet= ord("A") for i in range (6,1,-1): for j in range(1,i-1): character=chr(alphabet) print(character, end=" ") alphabet +=1 print()
num1 = int(input("Enter your 1st number")) num2 = int(input("Enter your 2nd number")) if num1==num2 or num1+num2==7: print("Hurray")
import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.stats as stats import sklearn marketing = pd.read_csv("C:\\Users\\app\\Desktop\\marketing.csv") marketing.head() type(marketing) marketing.columns marketing.corr() X = marketing.as_matrix(['youtube', 'facebook']) Y = marketin...
""" @Project: pytorch-learning-tutorials @File : simpleNet.py @Author : panjq @E-mail : pan_jinquan@163.com @Date : 2019-03-09 13:59:49 """ import torch from torch import nn from torch.nn import functional as F class SimpleNet(torch.nn.Module): def __init__(self): s...
import psutil from io import open file_path = "content.txt" content = u'''Python is a programming language that lets you work quickly and integrate systems more effectively.''' f1 = open(file_path, "a") f1.write(content) f1.write(u"\n") f1.close() ''' #读文件内容 f2 = open(file_path, 'r') #不带参数的read()函数一次读入文件的所有内容 p...
def is_palindromic(num): """Return true if the number is palindromic and false otehrwise""" return str(num) == str(num)[::-1] def dividable_with_indigits(num, digits): """Returns true if num is a product of two integers within the digits range""" within = range(10 ** digits - 1) for n in within[1:]...
def largest_prime(input_num): """returns the largest prime factor of a num""" largest = None num = input_num n = 2 while n ** 2 <= input_num: while num % n == 0: num = num / n largest = n n += 1 if largest is None: return input_num return largest def m...
def selectsort(arr): sorted = [] for i in range(len(arr)): sorted += [min(arr)] arr.remove(min(arr)) return sorted arr = [4,5,1,6,2,2,5,5,3,3,6] print(selectsort(arr))
def valid(s): valid = True if len(s)%2 != 0: valid = False return valid for i in range(1,len(s),2): if (s[i-1] == '(' and s[i] != ')') or (s[i-1] == '{' and s[i] != '}') or (s[i-1] == '[' and s[i] != ']'): valid = False return valid ...